我正在尝试为没有.html扩展的漂亮URL设置一个Nginx配置。
我现在拥有的东西可以工作,但是/ URI重定向到/index,我不想那样做。
URL重写规则应如下所示:
/index.html -> /
/test.html -> /test
/subpage/ -> /subpage
/subpage/test.html -> /subpage/test
/sub/sub/index.html -> /sub/sub
/sub/sub/ -> /sub/sub
/somepage/ -> /somepage
/somepage.html -> /somepage以下是配置:
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
set $root /app/www/public;
if (!-d /app/www/public) {
set $root /config/www;
}
root $root;
index index.html;
error_page 401 /401;
error_page 403 /403;
error_page 404 /404;
error_page 500 502 503 504 /500;
location / {
#redirect index.html to /
if ( $request_uri ~ "index.html" ) {
rewrite ^(.*)/ $1/ permanent;
}
#remove .html from request
rewrite ^/(.*)\.html$ /$1 permanent;
#remove the trailing /
rewrite ^/(.*)/$ /$1 permanent;
try_files $uri.html $uri/ $uri =404;
}
location ~* \.(jpg|jpeg|png|gif|ico)$ {
expires 30d;
}
location ~* \.(css|js)$ {
expires 7d;
}
# deny access to .htaccess/.htpasswd files
location ~ /\.ht {
deny all;
}
}注意:这个Nginx运行在一个码头容器中。
发布于 2022-09-20 19:26:17
我在nginx/1.18.0 (Ubuntu)上测试了这个配置:
index XXXXXX.DISABLE.INDEX.DOCUMENT.XXXXXX;
location / {
#remove index.html from request
rewrite ^/(.*)/index(\.html)?$ /$1 permanent;
rewrite ^/(.*)index(\.html)?$ /$1 permanent;
#remove .html from request
rewrite ^/(.*)\.html$ /$1 permanent;
#remove the trailing /
rewrite ^/(.*)/$ /$1 permanent;
try_files $uri ${uri}/index.html ${uri}.html =404;
}通过禁用index功能,您可以处理将index.html添加到与重写规则更兼容的try_files中。
您可以通过更改/sub/index.html和${uri}.html在try_files中的顺序来控制/sub请求是否优先于${uri}/index.html或D8。
测试:
curl --head http://localhost/ -> 200 OK (由/index.html供电)curl --head http://localhost/index -> 301 Moved Permanently to Location: http://localhost/curl --head http://localhost/index.html -> 301 Moved Permanently to Location: http://localhost/curl --head http://localhost/page -> 200 OK (由/page.html供电)curl --head http://localhost/page.html -> 301 Moved Permanently to Location: http://localhost/pagecurl --head http://localhost/sub -> 200 OK (由/sub/index.html供电)curl --head http://localhost/sub/ -> 301 Moved Permanently to Location: http://localhost/subcurl --head http://localhost/sub/ -> 301 Moved Permanently to Location: http://localhost/subcurl --head http://localhost/sub/index -> 301 Moved Permanently to Location: http://localhost/subcurl --head http://localhost/sub/index.html -> 301 Moved Permanently to Location: http://localhost/subhttps://webmasters.stackexchange.com/questions/140433
复制相似问题