簡體   English   中英

htaccess 如何重寫這個 url

[英]htaccess how to rewrite this url

如何重寫這個 URL:

https://example.com/illustrations.php?category=cats&cat_id=1

至:

https://example.com/category/cats

另外,我如何仍然保留cat_id參數?

我試過這個但它不起作用:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/?category/(.*?)/?$ /illustrations.php?category=$1 [L]

當我將此代碼和 go 添加到illustrations.php?category=cats它不會更改瀏覽器欄中的 URL。

對,那是正確的”。

The code you posted internally rewrites the URL /category/cats (which is the URL you should be linking to in your HTML source) back to the actual filesystem/URL path: /illustrations.php?category=cats . 這是使“漂亮的” URL /category/cats “工作”所必需的。

您不能僅使用.htaccess更改 URL 結構 - 如果這是您所暗示的。 您確實需要實際更改 HTML 源中的物理 URL。

You could implement an external redirect (not a rewrite) from /illustrations.php?category=cats to the canonical URL /category/cats using .htaccess , but note that this is only to benefit SEO (and third parties that might have already linked to舊網址)。 如果您要更改現有的 URL 結構並且 SEO 是一個問題,這是一個必要的附加步驟,但這不是您網站“工作”的一部分。

我如何仍然保留cat_id參數

您需要在 URL 中包含cat_id參數的 例如。 /category/cats/1 (正如@arkascha 在評論中建議的那樣)或/category/1/cats - 取決於哪個值更重要。 我會把更重要的價值放在第一位,因為 URL 在共享時可能會被意外裁剪。

 RewriteEngine on RewriteCond %{REQUEST_FILENAME}?-f RewriteCond %{REQUEST_FILENAME}.-d RewriteRule ^/?category/(?*.)/?$ /illustrations.php?category=$1 [L]

這條規則可以簡化。 文件系統檢查相對昂貴。 看起來你可以通過使你的正則表達式更具體來刪除這兩個。 例如。 /category/1/cats可以將 map 保存到文件中嗎? 您需要可訪問目錄嗎? 我希望這兩個問題的答案都是“不”。

我還將決定是否允許尾部斜杠,而不是允許兩者(如您當前的規則)。 嚴格來說,這會創建重復的內容(兩個 URL;相同的內容),因此需要額外的步驟來解決。 您的示例 URL 不包含尾部斜杠。

因此,您可以將規則簡化為以下內容,以便將/category/1/cats (無尾隨斜杠)重寫為/illustrations.php?category=cats&cat_id=1

RewriteEngine On
RewriteRule ^category/(\d+)/([\w-]+)$ /illustrations.php?category=$2&cat_id=$1 [L]

這假設cat_id可以是 1 個或多個數字( 0-9 )。 並且category僅限於以下字符: azAZ0-9_ (下划線)、 - (連字符)。

對於正則表達式,最好盡可能限制。 通過在上述規則的最后一個路徑段中省略點 ( . ),它不能匹配物理文件(假設所有文件都有文件擴展名)。

暫無
暫無

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

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