I am quite new to managing http server. How should I configure nginx to achieve behaviour like this: When there is a request for example.com/foo, nginx should serve index.html from /var/www/foo directory. When there is a request for example.com/bar, nginx should serve index.html from /var/www/bar directory.

The second part of URL (foo, bar) should not be hardcoded in nginx.conf, I need something like variable.

This is part of my nginx.conf, I tried something with variable in location section but I can't get this working.

server {
        listen       188.xxx.xxx.xxx;

        #access_log  logs/localhost.access.log  main;

        location ~/(\d+) {
            root   /var/www/$1;
            index  index.html index.htm;
  • 1
    You don't need to do anything special for this! Set root /var/www; and you're done. – Michael Hampton Apr 2 '14 at 19:37
  • This indeed works, however only if I call http://188.xxx.xxx.xxx/foo or http://188.xxx.xxx.xxx/bar. How to get this working with my domain: http://example.com/foo, http://example.com/bar ? I tried putting server_name example.com;, but didn't help. – user1091733 Apr 2 '14 at 20:47

You just need to set the root folder to make things work as expected.

Setting this within server {...} directive is enough, no need to specify a sub location directive.

Like this :

server {
   listen 188.xxx.xxx.xxx:80;
   server_name example.com;
   root /var/www;
   index  index.html index.htm;

Then, just ensure you have index.html or index.htm in

  • /var/www/foo
  • /var/www/bar
  • /var/www/whateveryouwant
  • Working great but only when URL is like this http://188.xxx.xxx.xxx/foo. when I change the address to http://example.com/foo I get 403 Forbidden. Do you have any idea why this is happening? – user1091733 Apr 2 '14 at 21:55
  • @user1091733 Should not happens. Please can you update your question with your vhost config ? There is certainly a bad config somewhere. – krisFR Apr 2 '14 at 21:58
  • @user1091733 My idea is that DNS does not resolve example.com with ip 188.xxx.xxx.xxx. Check DNS resolution. – krisFR Apr 2 '14 at 22:08
  • Thank you for response. Weird thing - if i put index.html into /var/www and go to http://example.com - I get the proper result. The problem appears only if I try to access index.html located in /var/www/foo by entering http://example.com/foo - then I get 403 Forbidden. My vhost config looks excatly like the one you posted in your answer. – user1091733 Apr 2 '14 at 22:42
  • @user1091733 It could be a permission issue. Check for the x bit for others on /var/www/foo folder : chmod o+x /var/www/foo – krisFR Apr 2 '14 at 22:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.