1

I have thousands of text files named like ABC. I'd like to access those files from different URL: - if it is ABC or ABC.txt I'd like to add default_type text/plain and serve that file - if it is ABC.html I'd like to add default_type text/html and serve that file (so that I have two different versions of the same file).

Is it possible to do that in nginx? The fact that one url could only be matched with one location directive causes me trouble in finding a "clean" way.

1
  • I've modified the question to clarify that it should match a pattern.
    – jcisio
    Dec 8, 2012 at 6:18

2 Answers 2

1

You should try to create a separate location for each file extension and use a internal redirect. It'll be something like that:

location /ABC.txt {
  add_header Content-Type text/plain;
  rewrite /ABC last;
}
location /ABC.html {
  add_header Content-Type text/html;
  rewrite /ABC last;
}
location /ABC {
  alias /var/www/ABC.txt
}

I don't promise it'll work because I have not tested it on a real nginx.

3
  • I could modify your settings to match a pattern with regular expression. However the tricky part is there is no content-type header if it is accessed without extension, and nginx uses "Content-Type: application/octet-stream".
    – jcisio
    Dec 8, 2012 at 6:21
  • To add a content type even when file is accessed without extension just add one more location with add_header parameter. Dec 8, 2012 at 9:45
  • I tested and it did not work. I always get the text/plain, with or without .html dev.jcisio.com/paste/Nfe74Cxf
    – jcisio
    Dec 8, 2012 at 10:24
1

nginx processes the suggested mimetype based on the URI. I tried the following combination and it works:

    root /usr/share/nginx/www;

    default_type text/plain;

    location = /abc.txt {
      alias /usr/share/nginx/www/abc;
    }

    location /abc.html {
      alias /usr/share/nginx/www/abc;
    }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .