簡體   English   中英

htaccess為網址加上.html擴展名(帶斜線或不帶斜線)

[英]htaccess add .html extension for urls with or without trailing slash

所以首先,我有一個自定義的URL重寫,它將請求變量發送到php腳本

重寫規則如下:

RewriteRule ^([\w\/-]+)(\?.*)?$ test/index.php?slug=$1 [L,T=application/x-httpd-php]

因此,如果您訪問domain.com/slug-textslug-text ,它將把slug-text發送到名為test的文件夾中的index.php

我想要的是所有URL都看起來像domain.com/slug-text.html ,但是slug-test變量仍應發送到index.php文件。

我不知道的是重定向。 我希望所有舊的URL從domain.com/slug-textdomain.com/slug-text/重定向到domain.com/slug-text.html並將slug-text發送到位於測試文件夾中的index.php文件。

進行了大量搜索,但是在Internet上的任何地方都找不到該問題的答案。

謝謝大家的幫助。

更新:我的新代碼是:

RewriteEngine On
Options +FollowSymlinks

RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(([\w/\-]+)?[\w-])(?!:\.html)$ http://domain.com/$1\.html [L,R=301]
RewriteRule ^(([\w/\-]+)?[\w-])(/|\.html)?$ test/index.php?slug=$1 [L]

domain.com/slug-text/不會重定向到domain.com/slug-text.html domain.com/slug-text可以按預期的方式重定向到domain.com/slug-text.html

我需要更改什么?

這條規則:

RewriteRule ^(([\w/\-]+)?[\w-])(/|\.html)?$ test/index.php?slug=$1 [L]

將陷阱domain.com/slug-textdomain.com/slug-text/domain.com/slug-text.html和發送slug-text/test/index.php里面slug PARAM。

如果您確實想使用[R=301]從舊網址重定向到新網址,請使用以下命令:

RewriteRule ^(([\w/-]+)?[\w-])/?(?!:\.html)$ http://domain.com/$1.html [L,R=301]
RewriteRule ^(([\w/-]+)?[\w-])\.html$ test/index.php?slug=$1 [L]

還要注意,由於使用了顯式重定向,底部規則已被修改以捕獲以.html結尾的url

還建議(如果您的.htaccess中尚未包含此內容)為不被重定向規則捕獲的現有文件和文件夾篩選條件。 只需在RewriteRule行之前添加以下行:

# existing file
RewriteCond %{SCRIPT_FILENAME} !-f
# existing folder
RewriteCond %{SCRIPT_FILENAME} !-d

如果使用符號鏈接:

# enable symlinks
Options +FollowSymLinks
# existing symlink
RewriteCond %{SCRIPT_FILENAME} !-l

//加法
您的.htaccess文件應如下所示:

RewriteEngine on
Options +FollowSymLinks
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-l
RewriteRule ^(([\w/-]+)?[\w-])/?(?!:\.html)$ http://domain.com/$1.html [L,R=301]
RewriteRule ^(([\w/-]+)?[\w-])\.html$ test/index.php?slug=$1 [L]

這應該將/ slug-text重定向到/slug-text.html

RedirectMatch ^/([\w-]+)/?$ http://domein.com/$1.html 

當“條狀文字”僅是字母,數字,-和_時,就是這種情況。 將slug-text.html重寫為php文件,並將slug作為參數傳遞:

RewriteRule ^([\w-]+)\.html$ test/index.php?slug=$1 [R,L] 

如果您的.htaccess中都有這兩行,則第一個將執行從舊URL到新URL的重定向,第二個將處理請求。

暫無
暫無

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

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