.htaccess rewrite regex: match anything but “index”

后端 未结 3 1881
孤城傲影
孤城傲影 2021-02-20 00:31

I\'m trying to create a rule used in a .htaccess file to match anything but a particular string, in this case: index.

I thought that it sho

相关标签:
3条回答
  • 2021-02-20 00:43

    You can use RewriteConds to do this, for example:

    RewriteCond %{REQUEST_URI} !^index
    RewriteRule (.*) index.php?what=$1
    

    That will rewrite every URL which doesn't start by index. If you want it to avoid it anywhere in the URL, remove the ^

    0 讨论(0)
  • 2021-02-20 00:45

    Apache used three different regular expression implementations. The first was System V8, since Apache 1.3 they used POSIX ERE and since Apache 2 they use PCRE. And only PCRE supports look-ahead assertions. So you need Apache 2 to use that rule.

    But now to your question. If you use this rule:

    RewriteRule ^index/ - [L]
    

    anything that starts with /index/ should be catched by this rule and no further rule should be applied.

    But if that doesn’t work, try this:

    RewriteRule !^index/ …
    

    Again, this rule will be applied on any request that’s URL path doesn’t start with /index/.

    And if you want to capture anything from the URL, use a RewriteCond condition to test either the full URL path itself (%{REQUEST_URI}) or just the match of one of your pattern groups:

    RewriteCond %{REQUEST_URI} !^/index/
    RewriteRule (.*) …
    # or
    RewriteCond $1 !^index$
    RewriteRule ^([^/]+)/(.*) …
    
    0 讨论(0)
  • 2021-02-20 00:56

    (Please read the comments. I doubt it and I've never encountered problems, while it gives one much cleaner .htaccess files, but: using RewriteCond might be preferred over using RewriteRule with a dash, due to how rulesets are processed?)

    Just use RewriteRule as follows, to not rewrite (the dash), and stop subsequent rewriting (the [L]) for anything that starts with index/:

    # Do not rewrite anything that starts with index/
    RewriteRule ^index/ - [L]

    After this, do any rewriting you like.

    Or maybe even limit some more first:

    # Do not rewrite files, directories or symbolic links 
    RewriteCond %{REQUEST_FILENAME} -f [OR] 
    RewriteCond %{REQUEST_FILENAME} -d [OR] 
    RewriteCond %{REQUEST_FILENAME} -l 
    RewriteRule . - [L]
    0 讨论(0)
提交回复
热议问题