简体   繁体   English

防止规则与htaccess的RewriteRule冲突

[英]Prevent rules conflicts with htaccess' RewriteRule

I would like to use some RewriteRule s to transform : 我想使用一些RewriteRule来转换:

Here is the htaccess : 这是htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?id=$1 [L]
RewriteRule ^(.*)/(.*)$ /index.php?id=$2&user=$1 [L]
</IfModule>

But it seems that the two last rules are incompatible : with this htaccess , I get some 500 Internal Server Error . 但是似乎最后两个规则是不兼容的:使用此htaccess ,我收到一些500 Internal Server Error

How to create two rules such that they do not "overlap" each other? 如何创建两个规则,以使它们彼此不“重叠”?

Notes : 注意事项:

  • each of these 2 rules work alone 这两个规则中的每一个单独起作用

  • when I use the second rule, then http://example.com/someone/blah => index.php?id=blah&user=someone works, but it seems that the root folder is no more / but /someone/ and then the CSS are not found... How to prevent the base folder to be changed in this case ? 当我使用第二条规则时,则http://example.com/someone/blah => index.php?id=blah&user=someone可以工作,但是似乎根文件夹不再是/ but /someone/ ,然后找不到CSS ...在这种情况下如何防止更改基本文件夹?

You have 4 issues: 您有4个问题:

  1. your first rule (.*) will convert anything into /index.php?id=$1 您的第一个规则(.*)会将任何内容转换为/index.php?id=$1
  2. your second rule does not verify if a file or folder exists and might fall into a infinite loop causing a 500 internal server error . 第二条规则不验证文件或文件夹是否存在,并且可能陷入无限循环,从而导致500 internal server error
  3. the order of your rules 规则的顺序
  4. you're using relative paths to serve CSS and Images which causes it to fail with your URL formats, such as domain.com/anything/anything 您正在使用相对路径来提供CSS和图片,这会导致您的URL格式(例如domain.com/anything/anything失败

To fix the redirect issue, you can use this: 要解决重定向问题,可以使用以下方法:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    RewriteRule ^index\.php$ - [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)/([^/]+)$ /index.php?id=$2&user=$1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]+)$ /index.php?id=$1 [L]
</IfModule>

Since I've changed the regex (to ([^/]+) which means anything not a / ) that catches the data you want and the order won't matter in this scenario as it will specifically match: 由于我已经更改了可捕获所需数据的正则表达式(改为([^/]+) ,表示不是/任何东西),因此在这种情况下顺序无关紧要,因为它会特别匹配:

domain.com/anything

And

domain.com/anything/anything

To fix the CSS and Images you can use the base TAG to define your absolute URL into your HTML: 要修复CSS和图片,您可以使用base TAG在HTML中定义绝对URL:

<base href="http://domain.com/">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM