簡體   English   中英

htaccess無法正常工作

[英]htaccess doesn't work as expected

我有一個htaccess重寫URL,如下所示:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.mywebsite.com$ [NC]
RewriteRule ^(.*)$ http://mywebsite.com/$1 [R=301,L]

RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f


RewriteRule ^my-page\.html$ /my-page.php [L]
RewriteRule ^my-page/([^/]*)\.html$ /level1.php?num=$1 [L]
RewriteRule ^my-page/([^/]*)/([^/]*)\.html$ /level2.php?level1=$1&level2=$2 [L]
RewriteRule ^([^/]*)\.html$ /level3.php?level3=$1 [L]

上面的這些規則將URL從mywebsite.com/my-page.php重寫為mywebsite.com/my-page.html

現在,我要實現的是將mywebsite.com/my-page/重定向到mywebsite.com/my-page.php (這又將重寫為mywebsite.com/my-page.html )。

我嘗試過的工作是創建目錄“ my-page”,並嘗試將請求從mywebsite.com/my-page/重定向到/my-page.html

我不知道出了什么問題。 我可以在網絡標簽中看到對/my-page/的請求已被重寫為mywebsite.com/my-page.htmlmy-page/ ,狀態為302☹

請幫忙! 謝謝。

您可以嘗試使用RedirectMatch實現此目的。

重定向到my-page.php:

RedirectMatch 301 ^/my-page/ http://mywebsite.com/my-page.php

或直接訪問my-page.html(如果這是您的目標):

RedirectMatch 301 ^/my-page/ http://mywebsite.com/my-page.html

或者,最好的方法是-更改負責mywebsite.com/my-page.htmlmy-page/的代碼,但我看不到您提出的問題:)

請嘗試以下方法。 在每個部分的注釋中都有簡要說明。

RewriteEngine On

# Trim www.
RewriteCond %{HTTP_HOST} ^www\.mywebsite\.com$ [NC]
RewriteRule ^(.*)$ http://mywebsite.com/$1 [R=301,L]

RewriteBase /

# Redirect /my-page[/] to /my-page.html
# >> Note: change 302 to 301 to make permanent
RewriteRule ^my-page/?$ my-page.html [R=302,L]

# Allow existing files and directories
# Recommended to comment out the first line
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# Rewrite *.html to respective page
RewriteRule ^my-page.html$ my-page.php [L]
RewriteRule ^my-page/([^/]*).html$ level1.php?num=$1 [L]
RewriteRule ^my-page/([^/]*)/([^/]*).html$ level2.php?level1=$1&level2=$2 [L]
RewriteRule ^([^/]*).html$ level3.php?level3=$1 [L]

此處的重要部分是您必須進行必要的重定向,然后再進行其他任何重寫( www.刪除除外)。

另外,您先前有兩個條件,條件是如果請求不是針對文件或目錄的,則繼續執行下一條規則,但這不會解釋最后兩個規則。 這樣,如果請求是針對現有文件或目錄的,此版本將告訴Apache停止所有操作。 為了安全起見,我建議您注釋掉檢查現有目錄的行。

暫無
暫無

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

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