Nginx – Dynamic URL in nginx configuration

nginx

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;
        }
}

Best Answer

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
Related Topic