我的根目錄中有這些檔案,在頁面內部我有 php 檔案,例如 projects.php,我嘗試撰寫 .htaccess 規則以獲取檔案,例如 xxx.com/projects 從 /pages/projects.php 打開檔案和它適用于以下
RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} . [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]
# No file extension on request then append .php and rewrite to subdir
RewriteCond %{REQUEST_URI} /(. )
RewriteRule !\.[a-z0-4]{2,4}$ /pages/%1.php [NC,L]
# All remaining requests simply get rewritten to the subdir
RewriteRule (.*) /pages/$1 [L]
我的問題是當我轉到根 xxx.com 而不是打開 index.php 它的打開頁面目錄時,但是如果我明確地轉到 xxx.com/index.php 它可以作業。我不希望 index.php 顯示在 url 我需要從我的規則中排除根并使其打開 index.php 而 url 保持 xxx.com
uj5u.com熱心網友回復:
# All remaining requests simply get rewritten to the subdir RewriteRule (.*) /pages/$1 [L]
要排除“根”被重寫/pages/(并index.php從根提供服務),您可以簡單地將最后一條規則中的量詞從*(0 或更多)更改為 (1 或更多) - 這樣它就不會匹配請求root ( 中的空 URL 路徑.htaccess)。
換句話說:
RewriteRule (. ) /pages/$1 [L]
順便說一句,您已經通過在CondPattern 中使用,在前面的規則/條件中做了類似的事情,即。. RewriteCond %{REQUEST_URI} /(. )
uj5u.com熱心網友回復:
我想到了另一個解決方案:
RewriteEngine On
RewriteBase /
# Hide the "pages" directory and all PHP files from direct access.
RewriteRule ^pages\b|\.php$ - [R=404]
# Rewrite clean-URL pages to the PHP files inside the "pages" directory:
# If the request isn't a file.
RewriteCond %{REQUEST_FILENAME} !-f
# If the request isn't a folder.
RewriteCond %{REQUEST_FILENAME} !-d
# If the PHP page file exists.
RewriteCond %{DOCUMENT_ROOT}/pages/$0.php -f
# /your-page?param=foo is rewritten to /pages/your-page.php?param=foo
# The L flag isn't suffisient because the rewrite rule to protect PHP files
# above will take over in the second loop over all the rewrite rules. To stop
# here we can use the newly END flag which stops completely the rewrite engine.
RewriteRule ^.*$ pages/$0.php [END,QSA]
你想躲起來index.php。這可以通過 404 錯誤來完成。所以你可以這樣做:
RewriteRule ^index\.php - [R=404]
但是您可能還希望避免有人要求/pages列出所有 PHP 檔案或直接訪問/pages/your-page.php. 所以我用一個正則運算式匹配的目錄和PHP檔案擴展名都(只有小寫這里,但你可以使用\.(?i)php其中(?i)允許的情況下我nsensitive標志)。
然后,對于重寫本身,我將捕獲^.*$在$0反向參考中可用的 URL,然后可以在重寫規則本身和重寫條件中使用該 URL 。
如果請求不是目錄或現有檔案,那么我們必須檢查生成的重寫 URL 是否實際上是pages目錄中現有的 PHP 檔案。
我使用了該QSA標志,以便您將查詢引數保留在結果 URL 中。然后 PHP 腳本可以通過$_GET. 如果您不使用此標志,我希望您也可以通過檢查其他一些環境變數來獲取它們。我也只好用END它類似于旗L為大號AST的國旗,但完全停止重寫規則來執行。如果您使用該L標志,問題是您將收到 404 錯誤,因為/pages/your-page.php將匹配重寫規則以隱藏 PHP 檔案,因為重寫規則的整個程序是第二次運行。僅當輸入 URL 不再被重寫規則更改時,重寫引擎回圈才會停止。是的,我花了很長時間才明白,重寫規則不僅僅運行一次,就像它們顯示在組態檔中一樣!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/407611.html
標籤:
