0

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;
        }
}
2
  • 1
    You don't need to do anything special for this! Set root /var/www; and you're done. Commented Apr 2, 2014 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.
    – polmarex
    Commented Apr 2, 2014 at 20:47

1 Answer 1

0

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
6
  • 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?
    – polmarex
    Commented Apr 2, 2014 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
    Commented Apr 2, 2014 at 21:58
  • @user1091733 My idea is that DNS does not resolve example.com with ip 188.xxx.xxx.xxx. Check DNS resolution.
    – krisFR
    Commented Apr 2, 2014 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.
    – polmarex
    Commented Apr 2, 2014 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
    Commented Apr 2, 2014 at 22:48

You must log in to answer this question.

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