Display any file in a browser as plain text

Here’s how to add Content-Type: text/plain with NGINX to all files inside a given directory.

The matching rules come from the same NGINX location directive used for redirects.

If you don’t want to download or execute a file, but only view it as raw text in the browser, as with .txt files, you can tell the web server to render it as plain text by setting the content type in the headers:

Content-Type text/plain

Edit headers with NGINX

With NGINX you can do it like this:

location test.php {
  add_header Content-Type text/plain;
}

That goes into your NGINX server block file. It only targets a single file. You can add a regex to target all files in a specific directory, for instance:

# Target code dir
location /code/ {
  # All files in it
  location ~* {
    add_header Content-Type text/plain;
  }
}