
如何從 Nginx 中的 url 字串中刪除所有 .html 副檔名以及任何出現的 index.html
http://www.mysite/index.html
到http://www.mysite
http://www.mysite/articles/index.html
到到http://www.mysite/articles
http://www.mysite/contact.html
http://www.mysite/contact
http://www.mysite/foo/bar/index.html
http://www.mysite/foo/bar
編輯:這是我的conf檔:
伺服器 {
listen 80;
server_name staging.mysite.com;
root /var/www/staging.mysite.com;
index index.html index.htm;
access_log /var/log/nginx/staging.mysite.com.log spiegle;
#error_page 404 /404.html;
#error_page 500 503 /500.html;
rewrite ^(.*/)index\.html$ $1;
rewrite ^(/.+)\.html$ $1;
rewrite ^(.*/)index\.html$ $scheme://$host$1 permanent;
rewrite ^(/.+)\.html$ $scheme://$host$1 permanent;
location / {
rewrite ^/about-us /about permanent
rewrite ^/contact-us /contact permanent;
try_files $uri.html $uri/ /index.html;
}
}
答案1
作為重寫(將剝離的 URL 傳遞到檔案系統/後端,而不更改顯示給客戶端的 URL):
rewrite ^(.*/)index\.html$ $1;
rewrite ^(/.+)\.html$ $1;
或者您可以執行 301 重定向(客戶端發出新請求):
rewrite ^(.*/)index\.html$ $scheme://$host$1 permanent;
rewrite ^(/.+)\.html$ $scheme://$host$1 permanent;
答案2
接受的答案似乎對我沒效。我是一個正在進行切換的 apache 人員,所以這可能無法在所有情況下 100% 工作,但這似乎在我的網站上工作(靜態 html 頁面,只是一個測試):
index index.html;
error_page 404 404.html;
rewrite ^(/.+)\.html$ $1;
try_files $uri.html $uri/ =404;
這就是讓這一切發生的原因:
- url => 它正在存取的文件
- 域名.com/=>index.html
- domain.com/somepage => somepage.html
- 網域.com/arandompage => 404.html
希望這能幫助其他困惑的前阿帕契主義者。