Home > other >  How to rewrite uri with location directive in nginx config
How to rewrite uri with location directive in nginx config

Time:05-02

I have searched many articles and posts but didn't find any particular fix for my requirement. Hence, posting this question.

I have 2 locations on my server /p1 and /p2. The default location should be /p1/index.html.

I want, when I will access http://localhost:8080/p1 or http://localhost:8080/p2 then I should be able to get the data from http://localhost:8080/p1/index.html, and also the URL should change in the browser.

Can we use any other directives instead of location directives to achieve this?

Below is the current Nginx config :

server {

      listen      80;
      root        /usr/share/nginx/html;

      location / {
      try_files $uri /p1/index.html;
      }
      
      location /p1 {
      try_files $uri /p1/index.html;
      }      

      location /p2 {
      try_files $uri /p1/index.html;
      }
}

Need in this way :

http://localhost:8080/p1 -->  http://localhost:8080/p1/index.html
http://localhost:8080/p2 -->  http://localhost:8080/p1/index.html

Any suggestion or help will be grateful.

CodePudding user response:

Got some clue from @BijayRegmi's comment. I have modified little and the below changes worked for me.

server {

      listen      80;
      root        /usr/share/nginx/html;

      location / {
      try_files $uri /p1/index.html;
      }
      
      location /p1 {
      try_files $uri /p1/index.html;
      }      

      location /p2 {
      return 301 $scheme://$http_host/p1/index.html;
      }
}
  • Related