[英]Apache2 .htaccess rewrite rule for nested URLs doesn't work
我有一個簡單的 php 應用程序,它具有基於domain/foo/bar
嵌套 url 的導航。
例如,我有主頁index.php
和about
nav 鏈接,它應該導航到domain/en/about
,其中en
和about
必須轉移到 url 參數,如index.php?url=...
。
但是當我點擊about
時,我進入了domain/en/about
並且404 not found 。
我已將 apache2 虛擬域配置配置為:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
<Directory /var/www/html/domain>
Options -Indexes +FollowSymLinks -MultiViews
AllowOverride All
Require all granted
</Directory>
DocumentRoot /var/www/domain/
ServerName domain.local
ServerAlias www.domain.local
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
和.htaccess
文件為:
order deny,allow
RewriteEngine On
RewriteBase /
RewriteRule .* index.php?url=$0 [QSA,L]
apache2 的mod_rewrite
已經啟用。
不知道我錯過了什么。
任何幫助表示贊賞! 先感謝您!
您需要在要捕獲的內容周圍加上括號。 反向引用索引以“1”開頭:
RewriteRule (.*) index.php?url=$1 [L,QSA]
<Directory /var/www/html/domain>: DocumentRoot /var/www/domain/
您的<Directory>
部分和DocumentRoot
指令引用不同的位置,因此無論您將.htaccess
文件放在哪里,它都不會按預期工作。
然而...
RewriteRule.* index.php?url=$0 [QSA,L]
這條規則並不嚴格正確,因為它最終會在重寫引擎第二次通過時重寫自己。 如果不是QSA
標志,原始的url
參數值(包含最初請求的 URL 路徑)將會丟失。 以上最終將/en/about
的請求重寫為index.php?url=index.php&url=en/about
。 幸運的是,您的 PHP 腳本仍將$_GET['url']
讀取為en/about
。 但是您可以檢查$_SERVER['QUERY_STRING']
中的完整(錯誤)查詢字符串。
(而且,如果您只是在替換字符串前加上斜杠,即 URL 路徑,您將得到一個無休止的重寫循環(500 內部服務器錯誤)。但這也可能是由於稍后添加其他規則造成的。 )
您應該防止對index.php
本身的請求被重寫,您可以通過添加附加規則來實現。 例如:
RewriteRule ^index\.php$ - [L]
RewriteRule .* index.php?url=$0 [QSA,L]
但是,這仍然會重寫您的 static 資產(假設您鏈接到內部圖像、CSS 和 JS 文件?)。 因此,如果請求已經映射到 static 文件,您通常需要使用一個附加條件來防止規則被處理。
例如:
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php?url=$0 [QSA,L]
CondPattern -f
檢查TestString是否映射到文件。 的!
前綴否定了這一點。 因此,只有當請求不map 到文件時,條件才成功。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.