nginx - 如何修复 ngnix.conf 以从 .html 和 index.html 重定向
问题描述
我想从网址重定向,这里存在真实页面 - mysite.com/folder/index.html:
- mysite.com/folder/index.html 到 mysite.com/folder/
- mysite.com/folder.html 到 mysite.com/folder/
- 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;
}
解决方案
您可以使用正则表达式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;
}
推荐阅读
- java - 仅当字段处于焦点时,如何使 TextFormatter 工作?
- ios - Swift 中 2 个初始化程序的奇怪问题
- php - 在多维php数组中搜索
- java - 具有两个@RequestMappings 的@RestController 类都具有相同的端点,一个没有参数,一个有参数
- swift - ObjectMapper 如何在嵌套实体中映射值
- javascript - 获取jsgrid中隐藏列的值
- c# - ListView 项目仅在滚动回视图后才会更新 - Xamarin Forms
- react-apollo - 如何在 prisma.yml 中设置“集群”属性
- java - 我可以在 DateTimeFormatter 对区域偏移格式进行更多控制吗
- opencl - NDRangekernel 增加后 GPU 驱动程序没有响应