8

I've got several static sites (mostly generated by Sphinx), that I'm trying to host on my VPS. I've installed and configured nginx according to the guides, and I can successfully display my sites, but the issue is the URLs are absolute, and it looks ugly.

For instance, a typical site folder may look like:

/public_html/index.html /public_html/api.html /public_html/quickstart.html

And HTTP requests to / change the URL to "http://sitename/index.html". I basically want to drop all static prefixes from the URL requirements, and force nginx to both route incoming requests to /, /api, /quickstart to the correct places as well as force nginx to display proper pretty URLs when users visit pages.

I've tried googling, but all I find is rewrite rules which I feel are too complicated for what I'm trying to do.

Any help would be greatly appreciated.

rdegges
  • 295
  • 1
  • 4
  • 7

2 Answers2

8

You should use try_files for this. The idea is that you will create your URLs without .html and Nginx will silently add it. Example config below.

server {
   #listen/server_name/root here.

   try_files $uri.html $uri $uri/ @notfound;

   location @notfound {
      alias /your/404/file.html
      return 404;
   } 
}
Martin Fjordvald
  • 7,749
  • 1
  • 30
  • 35
  • I don't want to actually show the .html suffix though. I prefer to have suffix-less URLs to handle future styles / conventions. – rdegges Oct 11 '10 at 02:18
  • That is exactly what this does. As I said just above the code example the URLs will be done with the .html and nginx will add it silently. – Martin Fjordvald Oct 11 '10 at 14:01
  • Following this answer doesn't quite work for me. If I have a file "can-you-see-me.html" that I would like the url to be /can-you-see-me, this causes the browser to download the file instead of displaying it. If I take out all of the dashes "canyouseeme.html" works fine with /canyouseeme, but I need the dashes..... – RyanBrady Nov 30 '11 at 21:03
  • please pipe my last comment to /dev/null. It started working last night. Not sure why - I am sure I reloaded the config more than once, but it's working now. – RyanBrady Dec 01 '11 at 13:47
2

Use static location:

location / {
        index index.html;
        root /var/www/nginx-default;
}

location /api {
        index api.html;
        alias /var/www/nginx-default;
}

location /quickstart {
        index quickstart.html;
        alias /var/www/nginx-default;
}

regexp:

location ~/(.*)$ {
        alias /var/www/nginx-default/$1.html;
}
bindbn
  • 5,211
  • 2
  • 26
  • 24