简体   繁体   中英

Nginx Rewrite domain to Subfolder excluding trailing slash

I am trying to rewrite a domain to include a language path but without the trailing slash.

So

www.example.com => www.example.com/en

www.example.com/page/ => www.example.com/en/page

www.example.com/page => www.example.com/en/page

I am currently using this config, but it is not working as expected.

server {
  listen 80;
  server_name www.example.com;
  root /var/www/example.com/public;
  rewrite ^/(.*)/$ /$1 permanent;

  index index.php index.html;

  location = / {
    return 301 http://www.example.com/en$request_uri;
  }
}

Mainly,

www.example.com => www.example.com/en/ => www.example.com/en

www.example.com/page => www.example.com/page

This code is also playing havoc on some of the http_post requests.

In the case of a POST, the redirect is downgraded to a GET (this is normal behaviour). The 307 response can be used to repeat a POST with the new URI. See this page for more.

In which case, you will need to rewrite your configuration to use return 307 statements. You can use regular expression location blocks to capture the URI without its trailing / . See this document for more.

One way to identify URIs that do not begin with /en , is to use a location ^~ /en block to process all URIs that do begin with /en , and use the regular expression location block to capture everything else.

For example:

location = / {
    return 307 /en;
}
location ~ ^(/.*?)/?$ {
    return 307 /en$1;
}
location ^~ /en {
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM