簡體   English   中英

htaccess 將所有頁面重定向到除根目錄之外的子目錄

[英]htaccess redirect all pages to subdirectory except root

在此處輸入圖像描述 I have these files in my root, Inside pages i have php files for example projects.php, I tried writing in .htaccess rules to take the file for example xxx.com/projects to open the file from /pages/projects.php and it與以下工作

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]

My problem here is when i go to the root xxx.com instead of opening index.php its opening pages directory but if i go explicitely to xxx.com/index.php it works. I dont want index.php to be shown in the url i need to exclude the root from my rule and make it open index.php while the url stays xxx.com

# All remaining requests simply get rewritten to the subdir RewriteRule (.*) /pages/$1 [L]

要排除“根”被重寫為/pages/ (並從根中提供index.php ),您可以簡單地將最后一條規則中的量詞從* (0 或更多)更改為+ (1 或更多) - 這樣它與對根的請求不匹配( .htaccess中的空 URL 路徑)。

換句話說:

RewriteRule (.+) /pages/$1 [L]

順便說一句,您已經通過在CondPattern中使用+在前面的規則/條件中做了類似的事情,即。 RewriteCond %{REQUEST_URI} /(.+)

我想到了另一個解決方案:

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)啟用不區分大小寫標志)。

然后,對於重寫本身,我將使用^.*$捕獲 URL ,它將在$0反向引用中可用,然后可以在重寫規則本身和重寫條件中使用。

如果請求不是目錄或現有文件,那么我們必須檢查生成的重寫 URL 實際上是pages目錄中現有的 PHP 文件。

我使用了QSA標志,以便將查詢參數保留在生成的 URL 中。 然后 PHP 腳本可以通過$_GET輕松訪問它們。 如果您不使用此標志,我希望您也可以通過檢查其他一些環境變量來獲取它們。 我還必須使用類似於L for L ast 標志的END標志,但完全停止執行重寫規則。 如果您使用L標志,問題是您將收到 404 錯誤,因為/pages/your-page.php將匹配重寫規則以隱藏 PHP 文件,因為重寫規則的整個過程都在運行第二次。 僅當輸入 URL 不再被重寫規則更改時,重寫引擎循環才會停止。 是的,我花了很長時間才明白,重寫規則不僅僅運行一次,就像它們顯示在配置文件中一樣!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM