我希望通過重寫使 URL 看起來干凈漂亮。我在使用 Apache 時能夠做到這一點,但我在服務器上安裝了 Nginx。所以我不使用.htaccess.
在使用 Apache 時,我是這樣使用它的:
<IfModule mod_rewrite.c>
SetEnv HTTP_MOD_REWRITE On
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_URI} !\.php$ [NC]
RewriteCond %{REQUEST_URI} [^/]$
RewriteRule ^(.*)$ $1.php [L]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteCond %{REQUEST_URI} !.(css|gif|ico|jpg|js|png|swf|txt)$
RewriteRule ^ - [L]
RewriteRule ^([^/] )/([^/] )?$ index.php?cmd=$1&scd=$2 [L,QSA]
RewriteRule ^([^/] )/?$ index.php?cmd=$1 [L,QSA]
</IfModule>
例如這個 URL 看起來像這樣:
https://example.com/item/1234/bund123
沒有 mod_rewrite:
https://example.com/index.php?item?id=1234&unt=bund123
我嘗試執行此 Nginx,但出現 404 錯誤。這可能是什么原因?
server {
listen *:80;
listen [::]:80;
listen *:443 ssl http2;
server_name example.com www.example.com;
root /var/www/example.com/web/;
rewrite ^([^/] )/([^/] )?$ /index.php?cmd=$1&scd=$2 last;
rewrite ^([^/] )?$ /index.php?cmd=$1 last;
....
}
我哪里做錯了?
uj5u.com熱心網友回復:
可以在 Nginx 錯誤日志中找到有關 404 錯誤的詳細資訊。據推測,index.php 不存在。
可以使用redirectCurl快速測驗重寫規則:
# /item/cmd/scd
rewrite ^/item/([^/] )/([^/] ) /index.php?cmd=$1&scd=$2 redirect;
# /item/cmd
rewrite ^/item/([^/] ) /index.php?cmd=$1 redirect;
$ curl -I https://example.com/item/CMD/SCD
HTTP/1.1 302 Moved Temporarily
Location: https://example.com/index.php?cmd=CMD&scd=SCD
$ curl -I https://example.com/item/CMD
HTTP/1.1 302 Moved Temporarily
Location: https://example.com/index.php?cmd=CMD
當重寫正常作業時,更改redirect為break:
rewrite ^/item/([^/] )/([^/] ) /index.php?cmd=$1&scd=$2 break;
rewrite ^/item/([^/] ) /index.php?cmd=$1 break;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/392551.html
標籤:正则表达式 .htaccess nginx 改写 url重写
上一篇:使用ajax顯示/隱藏元素
