.htaccess 刪除第一個 php url 參數(如果第二個存在)

.htaccess 刪除第一個 php url 參數(如果第二個存在)

這是我的 .htaccess 程式碼:

RewriteCond %{REQUEST_URI} !^/pages/ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)(/([^/]+))? pages.php?PAGE=$1&LINK=$3 [L]

*其中 $1 = 個人資料,$3 = 約翰史密斯

這重寫得很好,就像https://example.com/profile/john-smith但我需要第二個重寫規則,例如https://example.com/john-smith僅當包含 john-smith 的第二個參數存在時。

謝謝你!

更新:(我的 .htaccess 檔案的完整規則)

# protect files beginning with .
RewriteRule /\.(.*) - [NC,F]

# redirect HTTPS
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

# No root access without index.* and other security
RewriteEngine On
Options All -Indexes
RewriteBase /
DirectoryIndex index.php index.html index.htm
ErrorDocument 404 https://example.com/pages.php?PAGE=404

# Prevent upload malicious PHP files
<FilesMatch “\.(php|php\.)$”> 
Order Allow,Deny 
Deny from all 
</FilesMatch>

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [QSA,L]

RewriteCond %{REQUEST_URI} !^/pages/ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)(/([^/]+))? pages.php?PAGE=$1&LINK=$3 [QSA, L]

答案1

RewriteRule ^([^/]+)(/([^/]+))? pages.php?PAGE=$1&LINK=$3 [L]

這樣做的「問題」是,它還將匹配 的請求/john-smith(第二組是可選的),但將請求重寫為pages.php?PAGE=john-smith&LINK=, 而不是pages.php?LINK=john-smith按照要求重寫。為此,您需要一個單獨的規則。它還匹配/profile/john-smith/anything、丟棄/anything但仍然重寫請求(多對一關係),這可能會讓您的網站容易受到垃圾郵件發送者的攻擊。

假設您不允許.在 URL 路徑段中使用點 ( )(根據您的範例),則無需檢查請求是否未對應到檔案。例如。如果您的文件都具有文件副檔名,則請求/profile/john-smith永遠無法對應文件,因此檔案系統檢查是多餘的。

請嘗試以下方法:

# Rewrite exactly one path segment
# eg. /john-smith to pages.php?LINK=john-smith
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)$ pages.php?LINK=$1 [L]

# Rewrite exactly two path segments
# eg. /profile/john-smith to pages.php?PAGE=profile&LINK=john-smith
RewriteCond %{REQUEST_URI} !^/pages/ [NC]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/([^/.]+)$ pages.php?PAGE=$1&LINK=$2 [L]

NC前面的指令上的標誌可能RewriteCond是多餘的。

([^/.]+)- 我已經更改了捕獲子模式以排除點。第二條規則剛好符合兩個路徑段,而不是一個或者兩個路徑段,如您的範例所示。

相關內容