我的 .htacces 代碼有問題,因為它會產生 500 內部服務器錯誤而不是 404 錯誤,就像它應該的那樣。
500 內部錯誤僅在我嘗試在實際是檔案的目錄中打開頁面時引起。例如,在我網站的根目錄中,有檔案biography.php. https://example.com/biography.php重定向到https://example.com/biography/.
但是當我嘗試打開不存在的頁面時https://example.com/biography/test/,它顯示 500 內部服務器錯誤而不是預期的 404 錯誤。
這是我的 .htaccess 代碼。最后 6 行似乎導致了問題,因為沒有它們,將顯示預期的 404 錯誤而不是 500 內部服務器錯誤。但是沒有它們,https://example.com/biography.php不會重定向到https://example.com/biography/……
也許有一個重定向回圈或類似的東西?我只是從互聯網上復制了代碼,所以我無法自己解決問題。
Options -Indexes
AddDefaultCharset UTF-8
ServerSignature Off
DirectoryIndex index.php
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^example.com$ [NC]
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !(^$|\.[a-zA-Z0-9]{1,5}|/)$ %{REQUEST_URI}/ [R=301,L]
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^((/?[^/] ){1,2})/$ $1.php [L]
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.] )\.php [NC]
RewriteRule ^ %1 [R=301]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [NC,L]
感謝您的幫助!我希望你能理解我的問題!我很感激!:)
uj5u.com熱心網友回復:
RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*?)/?$ $1.php [NC,L]
重寫回圈(導致 500 錯誤)是由最后一條規則(3 個指令)引起的,因為檢查的條件%{REQUEST_FILENAME}.php -f不一定是檢查您在RewriteRule 替換字串(即$1.php)中重寫的同一個檔案。
當您請求時,/biography/test/您最終會檢查是否/biography.php存在(確實存在),但最終將請求重寫為/biography/test.php(不存在)-這會導致重寫回圈。
有關更詳細的解釋,請參閱我對 ServerFault 上以下問題的回答:https : //serverfault.com/questions/989333/using-apache-rewrite-rules-in-htaccess-to-remove-html-causing-a-500 -錯誤
最后一條規則應該這樣寫:
# Rewrite to append the ".php" extension as required.
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
現在,在將.php擴展名附加到相同的 URL-path之前,這會檢查目標檔案是否存在。
不需要兩個條件。并且NC這里不需要標志。
RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.] )\.php [NC] RewriteRule ^ %1 [R=301]
然而,你重定向到洗掉的.php擴展并不完全正確要么。.php如果它出現在 URL 的查詢字串部分,這也會錯誤地洗掉“擴展”。你錯過了L國旗。您也不需要這兩個條件。
使用類似以下內容:
# Remove ".php" extension from requested URL-path
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(. )\.php$ /$1 [R=301,L]
概括
# Remove ".php" extension from requested URL-path
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(. )\.php$ /$1 [R=301,L]
# Rewrite to append the ".php" extension as required.
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*?)/?$ $1.php [L]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/316586.html
