Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RewriteCond with negative conditions

I'm trying to rewrite all www.site.com/hello to www.site.com/index.php?p=hello and it works with the following code (in .htaccess):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ /index.php?p=$1

But I want to keep the old links working so www.site.com/?p=hello will stay www.site.com/?p=hello

I've tried the following code but it won't work

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\?p=)
RewriteRule ^([^/]*)/?$ /index.php?p=$1
like image 304
Itay Avatar asked Jun 02 '13 12:06

Itay


People also ask

What is the difference between rewriterule and rewriteconddirective?

The RewriteConddirective attaches additional conditions on a RewriteRule, and may also set backreferences that may be used in the rewrite target. One or more RewriteConddirectives may precede a RewriteRuledirective. That RewriteRuleis then applied only if the current state of the URI matches its pattern, and all of these conditions are met.

How can I prevent a rewriterule from being triggered?

You can move these conditions to their own block at the start of the .htaccess file and reverse their meaning, so instead of only triggering the RewriteRule when a request does not match the pattern (using a negated regex). You can prevent further rewrites when a request does match the pattern.

Can mod_rewrite skip the next rewriterules statement?

On the other hand, there is the Skip flag which tells mod_rewrite to SKIP (read GOTO) the next n RewriteRules (block statements). NOW, I must agree with l_e that your mod_rewrite code could use some improvement:

How to prevent mod_rewrite directives being processed?

Note the removal of the! (negation) prefix on the CondPattern and the additional OR flag on the first three conditions. The RewriteRule then prevents further mod_rewrite directives being processed should the request match.


1 Answers

I've found an answer.

The mistake was trying to get the GET parameters with REQUEST_URI. The right usage should be with QUERY STRING like this:

RewriteCond %{QUERY_STRING} !(p=.*)$ 
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?$ /index.php?p=$1
like image 70
Itay Avatar answered Sep 22 '22 05:09

Itay