George George - 1 month ago 6
Apache Configuration Question

htaccess internal rewrite for URL with query params

I have a php file

/var/www/somepath/index.php
which handles requests to

http://example.com/somepath/?q=query


I'd like the same file to handle requests to

http://example.com/some/other/path/?q=query
http://example.com/another/path/?q=query
http://example.com/yet/another/path/?q=query


I do not want to copy the php file into multiple locations in the filesystem. I thought using internal rewrite rules would be a better way to do do it. Here is what I put in top-level
.htaccess
file
/var/www/.htaccess
:

RewriteRule ^some/other/path /somepath/%{QUERY_STRING} [PT]


But it does not work. I get a 404 for http://example.com/some/other/path/?q=query

I know that mod_rewrite is enabled because I have external rewrite rules (301 and 302 redirects) in the same .htaccess files and those work.

Answer

You can place this rule as your very first rule in the site root .htaccess which will handle any URL with ?q= query parameter:

RewriteEngine On

RewriteCond %{QUERY_STRING} (^|&)q= [NC]
RewriteRule ^ somepath/index.php [L]