简体   繁体   English

Nginx将域重写为子文件夹,不包括尾部斜杠

[英]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 => www.example.com/en

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

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 => www.example.com/en/ => www.example.com/en

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

This code is also playing havoc on some of the http_post requests. 此代码也对某些http_post请求造成严重破坏。

In the case of a POST, the redirect is downgraded to a GET (this is normal behaviour). 在POST的情况下,重定向降级为GET(这是正常行为)。 The 307 response can be used to repeat a POST with the new URI. 307响应可用于使用新URI重复POST。 See this page for more. 请参阅此页面了解更多信息

In which case, you will need to rewrite your configuration to use return 307 statements. 在这种情况下,您需要重写配置以使用return 307语句。 You can use regular expression location blocks to capture the URI without its trailing / . 您可以使用正则表达式位置块来捕获URI而不使用其尾随/ 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. 识别不以开头的URI的一种方法/en ,是使用location ^~ /en块来处理那些开头的所有的URI /en ,并使用正则表达式所在地块来捕捉一切。

For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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