首页 > 解决方案 > 如何修复 ngnix.conf 以从 .html 和 index.html 重定向

问题描述

我想从网址重定向,这里存在真实页面 - 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;
 } 

第三种解决方案 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;    
    }

标签: nginxnginx-config

解决方案


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

例如:

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

location/符合您的第三个要求。


您的rewrite语句应该是安全的,但如果它们导致重定向循环,您可能需要将它们替换为if块并在$request_uri. 例如:

if ($request_uri ~ ^([^?]*?)(/index|)(\.html)(\?.*)?$) {
    return 301 $1/$4;
}

推荐阅读