Question:
Is it possible to clear the %{QUERY_STRING}
without breaking any functionality of what I've accomplished in my .htaccess file.
I want to prevent users from adding ?foo=bar
to the end of the url overwriting any predefined $_GET vars
(external re_write) Example:
From: example.com/foo/bar/hello/world?test=blah
To: example.com/foo/bar/hello/world
So far I have been able to accomplish this (internally):
From: example.com/foo/bar/hello/world
To: example.com/index.php?foo=bar&hello=world
.htaccess
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{THE_REQUEST} ^GET\s.+\.(?:html?|php|aspx?) [NC]
RewriteRule ^(.+)\.php$ /$1 [R=301,L,NC]
# To externally redirect /dir/index to /dir/
RewriteCond %{THE_REQUEST} ^GET\s((.+)?(\/)?)?(index) [NC]
RewriteRule ^(([^/]+/)*)index$ /$1 [R=301,L,NC]
# To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_URI} !\.php$ [NC]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule . %{REQUEST_URI}.php [L]
# Prevent Rewrite on existing directories, files, and links
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L] #^ - [L]
# To internally rewrite directories as query string
RewriteRule ^([^/=]+)=([^/]*)(/(.+))?\/?$ /$4?$1=$2 [N,QSA]
RewriteRule ^([^/=]+)/([^/=]+)(/(.+))?\/?$ /$4?$1=$2 [N,QSA]
RewriteRule ^([^/=]+)(/(.+))?\/?$ /$3?$1 [N,QSA]
What I've tried:
#if there is a query string
RewriteCond %{QUERY_STRING} ^(.*)$
RewriteRule (.*) $1? [R=301,L] #remove query string
-
#if there is a query string
RewriteCond %{QUERY_STRING} !=""
RewriteRule (.*) $1? [R=301,L] #remove query string
-
#if there is a query string
RewriteCond %{QUERY_STRING} !=""
RewriteRule ^(.*)$ $1? [R=301,L] #remove query string
I read somewhere, and experienced it, that applying the above breaks anything I've already accomplished. Completely clearing the whole url if they are masked $_GET vars. Even crashes apache 0.o (forgive me for any silly regex or .htaccess code, they're aren't my strong suite and most of it was snippets I found on SO)
is this possible? something I'm doing wrong?
thanks
Try:
You need to match against the actual request because you're building a query string with these rules:
When these rules loop around, the
%{QUERY_STRING}
variable will have stuff in it and your rules will clobber them. If you match against the actual request, your rewrites won't get affected.