Search code examples
.htaccesshttp-redirectmod-rewriteurl-rewritingquery-string

url variable is set after rewrite rule


RewriteCond %{THE_REQUEST} \s/+blog/index\.php\?c=([^\s&]+) [NC]
RewriteRule ^ blog/%1? [R=301,L]
RewriteRule ^blog/([\w-]+)?$ blog/index.php?c=$1 [L,QSA]

the above works fine
now I ned a rule if there is no c variable - just index.php

RewriteCond %{THE_REQUEST} \s/+blog/index\.php [NC]
RewriteRule ^blog/ [L,R=301,NE]  

php

if(isset($_GET['c'])){$cat = $_GET['c'];}
var_dump($cat); // empty string

I don't want the c variable to be set in the second case
what is the reason?


Solution

  • With your shown samples/attempts, please try following htaccess Rules. Please make sure to clear your browser cache before testing your URLs.

    RewriteEngine ON
    ##Rules for uris which have only index.php in it.
    RewriteCond %{THE_REQUEST} \s/(blog)/index\.php\s [NC]
    RewriteRule ^ %1/index.php? [L,R=301,NE,NC] 
    
    ##Rules for uris which have c variable added in it.
    RewriteCond %{THE_REQUEST} \s/(blog)/index\.php\?c=([^\s&]+)\s [NC]
    RewriteRule ^  %1/%2? [R=301,L]
    
    ##Rules for non-existent pages.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(blog)/([\w-]+)/?$  $1/index.php?c=$2 [NC,L,QSA]
    

    OR Above Rules sets do redirection to index.php for without query string URLs, in case you don't want to perform redirection then please try following rules, make sure either use above or following rules only one at a time.

    RewriteEngine ON
    ##Rules for uris which have only index.php in it.
    RewriteCond %{THE_REQUEST} \s/(blog)/index\.php\s [NC]
    RewriteRule ^ %1/index.php? [L,NC] 
    
    ##Rules for uris which have c variable added in it.    
    RewriteCond %{THE_REQUEST} \s/(blog)/index\.php\?c=([^\s&]+)\s [NC]
    RewriteRule ^ %1/%2? [R=301,L]
    
    ##Rules for non-existent pages.
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d    
    RewriteRule ^(blog)/([\w-]+)/?$ $1/index.php?c=$2 [NC,L,QSA]