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/foo/http://example.com/foo/bar/的请求将分别重写为http://example.com/index.phphttp://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。

但是,我的首选方法是将所有内容重定向到索引.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 文件。