簡體   English   中英

HTACCESS 規則重定向錯誤

[英]HTACCESS rules redirection error

在我的 htaccess 文件中,我添加了一條規則將 url/abc/xyz 重定向到 url/abc/xyz.php 所以現在即使我嘗試訪問 url/abc.php 它也會將我重定向到 url/abc/

幫我解決這個..我現在的代碼:

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s([^.]+)\.php\s [NC]
RewriteRule ^ %1 [R,L]

## To internally forward /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^(.*?)/?$ $1.php [L]

我想要的是:

url/abc.php & url/abc 應該轉到 url/abc.php

url/abc.php/#x & url/abc/#x 應該轉到 url/abc.php/#x

如果我正確解釋了您的意圖,以下重寫規則應該符合您的意願:

# Enable rewriting
RewriteEngine On

# Define site root
RewriteBase /

# Do not rewrite for image, css or js files
RewriteRule \.(css|jpe?g|gif|png|js)$ - [L]

# Add index.php to requests ending with a trailing slash
RewriteRule ^([a-z0-9_\-/]*/)?$ $1index.php [NC,R=301,L]

# Add .php to the end of a request without a trailing slash
RewriteRule ^(([a-z0-9_\-]+/)*[a-z0-9\-]+)$ $1.php [NC,R=301,L]

規則的作用:

  • 相對於域的根 (/) 進行重寫
  • 重寫規則將忽略具有規則 nr 2 中列出的文件擴展名的任何文件。
  • http://example.com/ (或http://example.com )、 http://example.com/index.php http://example.com/foo/http://example.com/foo/bar/請求將被重寫為http://example.com/index.php , http://example.com/foo/index.phphttp://example.com/foo/bar/index.php分別
  • http://example.com/bazhttp://example.com/baz/boo請求將被重寫為http://example.com/baz.phphttp://example.com/baz/boo.php分別

URL 片段 (#) 永遠不會發送到服務器,因此您不能使用 mod_rewrite 重定向它。 換句話說,# 只在瀏覽器中解釋,所以你不需要在 .htaccess 中擔心它。

這段代碼應該適合你,或者至少讓你開始:

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME}\.php -f
    RewriteRule ^(.*)$ $1.php
</IfModule>

我還將它包含在一個 IfModule 中,以檢查是否首先啟用了 mod_rewrite。

然而,我的首選方法是將所有內容重定向到 index.php,然后在那里放置 PHP 代碼,這些代碼將分解 URL 並重定向到適當的頁面。 這對於模型-視圖-控制器 (MVC) 系統和其他類似的變體非常有效。 這也允許從一個地方而不是多個地方加載一般站點設置。 這是我將用於此類設置的代碼:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_URI} !^/img/[0-9a-zA-Z_\-]+\.(gif|jpg|png)$
  RewriteCond %{REQUEST_URI} !^/css/[0-9a-zA-Z_\-]+\.css$
  RewriteCond %{REQUEST_URI} !^/js/[0-9a-zA-Z_\-]+\.js$
  RewriteRule ^.+$ index.php [L]
</IfModule>

前三行表示不重定向指定目錄中的任何圖像、css 或 js 文件。

暫無
暫無

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

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