如何修复nginx.conf以从.html和index.html重定向

问题描述 投票:1回答:1

我想从网址重定向,这里存在真实页面 - mysite.com/folder/index.html:

  1. mysite.com/folder/index.html到mysite.com/folder/
  2. mysite.com/folder.html到mysite.com/folder/
  3. mysite.com/index.html到mysite.com

这是我配置的一部分

server_name k.my.net www.k.my.net;

index index.html;
root /var/www/demo/k.my.net/current/public;

rewrite ^(.*/)index\.html$ $1;
rewrite ^(/.+)\.html$ $1/;

location / {   
    try_files $uri $uri/ =404;
}

还可以尝试:

 location / {
    try_files $uri $uri/ @htmlext;
  }

 location ~ \.html$ {
    try_files $uri =404;
 }

 location @htmlext {
   rewrite ^(.*)$ $1.html permanent;
 } 

第3个解决方案ERROR_LOOP

    location ~* ^/([a-zA-Z1-9_-]*/)index\.html$ {
      return 301 $1;
    }
    location ~* ^/([a-zA-Z1-9_-]*/?[1-9a-zA-Z_-]*)\.html$ {
     return 301 /$1/;
    }

   location ~* ^/([a-zA-Z1-9_-]*/?[a-zA-Z1-9_-]*)/$ {
     try_files /$1.html /$1/index.html =404;    
    }

nginx nginx-config
1个回答
0
投票

您可以使用正则表达式location在尾随/之前提取URI的一部分,并使用try_files来测试两个替代方案。有关详细信息,请参阅this document

例如:

location ~ ^(.*)/$ {
    try_files $1/index.html $1.html =404;
}

location也匹配/,这将满足您的第三个要求。


你的rewrite语句应该是安全的,但是如果它们导致重定向循环,你可能需要用if块替换它们并在$request_uri中测试原始请求。例如:

if ($request_uri ~ ^([^?]*?)(/index|)(\.html)(\?.*)?$) {
    return 301 $1/$4;
}
© www.soinside.com 2019 - 2024. All rights reserved.