如果頁面不存在,我希望從呼叫中排除規則。在我現有的 htaccess 中,當用戶訪問從根目錄不存在的頁面時,此規則按預期作業。奇怪的是,如果用戶嘗試訪問不存在的有效頁面的子目錄,它就不起作用。
我的 htaccess 的當前行為:
example.com/valid-page/ -> example.com/valid-page/ (good)
example.com/valid-page -> example.com/valid-page/ (good)
example.com/valid-page/valid-page -> example.com/valid-page/valid-page/ (good)
example.com/does-not-exist -> example.com/does-not-exist (good)
example.com/valid-page/does-not-exist -> example.com/valid-page/does-not-exist/ (boo!)
對于上面的壞例子,期望的結果應該是不包含正斜杠:
example.com/valid-page/does-not-exist -> example.com/valid-page/does-not-exist
這是.htaccess:
# Redirects for errors
ErrorDocument 404 /error.php
ErrorDocument 403 /error.php
# Hides directory file listings
Options -Indexes
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
# Force slash at end of URL
RewriteCond %{REQUEST_URI} / [^\.] $
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(. [^/])$ %{REQUEST_URI}/ [R=301,L]
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.] )\.php [NC]
RewriteRule ^ %1 [R,L]
# To internally forward /dir/foo to /dir/foo.php
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.] )/$ $1.php [NC,L]
uj5u.com熱心網友回復:
# Force slash at end of URL RewriteCond %{REQUEST_URI} / [^\.] $ RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(. [^/])$ %{REQUEST_URI}/ [R=301,L]
您需要更改針對 進行檢查的第二個條件REQUEST_FILENAME,因為當您請求時/valid-page/does-not-exist,REQUEST_FILENAME是.../valid-page,而不是.../valid-page/does-not-exist您所期望的。
而不是REQUEST_FILENAME,使用REQUEST_URI(或$1反向參考)并構造絕對檔案名。例如:
# Force slash at end of URL
RewriteCond %{REQUEST_URI} / [^\.] $
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule ^(. [^/])$ %{REQUEST_URI}/ [R=301,L]
您需要在測驗前清除瀏覽器快取,因為錯誤的 301(永久)重定向將被瀏覽器快取。使用 302(臨時)重定向進行測驗以避免快取問題。
現在,當您請求時,/valid-page/does-not-exist您正在檢查是否.../valid-page/does-not-exist.php作為檔案存在,而不是.../valid-page.php像以前那樣。
請參閱我對 ServerFault 上以下問題的回答,其中詳細介紹了REQUEST_FILENAME實際設定的內容。 https://serverfault.com/questions/989333/using-apache-rewrite-rules-in-htaccess-to-remove-html-causing-a-500-error
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/322377.html
