Ngnix: Solution for Directory Resolution Problem in Virtual Hosting
Nginx displays a peculiar but logical behavior when handling directories specified without the ending slash. For example you have a directory like http://www.example2.com/dir/. However you specify the url as http://www.example2.com/dir. Also assume that you have configured the server for virtual hosting and the alternative server names are: www.example.com, www.example2.com etc. and they are specified in the same order. Now when you try to fetch http://www.example2.com/dir you will instead be redirected to http://www.example.com/dir. Here is why nginx does it along with a simple solution to the rather baffling problem (ok complex problem - I said it).
Any decent web server, nginx and apache included, will redirect url like http://www.example2.com/dir to the proper url - http://www.example2.com/dir.
However nginx when internally redirecting (using 301) for a rewrite directive if the redirect is relative (has no host part), then when redirecting Nginx uses the "Host" header if the header match name of server_name directive or the first name of server_name directive, if the header does not match or is absent. If no server_name is set, then the local hostname is used.
If you want Nginx to always use the "Host" header as you would for virtual hosting, you can use _ as server_name as of 0.6.x. However there is a better way which I recommend. Use the following directives to use host header instead of server_name:
optimize_server_names off;
server_name_in_redirect off;
Additionally optimize_server_names has the benefit of improving the nginx server performance.
Filed under Headline News, How To, Linux, Web, Web Hosting, Web Services, nginx |
|
RSS 2.0 |
Trackback this Article
|
Email this Article
You may also like to read |





































July 10th, 2008 at 8:12 pm
[...] hosting server_name is set to the first server name in your server_name list. This can lead to directory resolution problems in nginx (read the linked article for an elegant solution) in addition to specifying a wrong value for [...]
July 12th, 2008 at 8:18 am
[...] Nginx: how to fix directory resolution issue as well as internal re-directs in virtual hosting [...]