Link to home
Start Free TrialLog in
Avatar of RegProctor
RegProctorFlag for United States of America

asked on

Apache rewrite with variable domain

I need to rewrite a URL from host/index.php to host/.

There are various solutions out there however they rely on the host being a constant, such as (1) below. When I try to make a simple adjustment to cater to a variable host such as (2) below I run into trouble.

Any help greatly appreciated.
(1)
RewriteCond ${REQUEST_URI} ^/index.php$
RewriteRule .* http://host/ [L,R=301]
 
(2)
RewriteCond ${REQUEST_URI} ^/index.php$
RewriteRule .* ${HTTP_HOST} [L,R=301]

Open in new window

Avatar of caterham_www
caterham_www
Flag of Germany image

You're using the rule in your httpd.conf?

That should be enough:
# httpd.conf
RewriteEngine on
RewriteRule ^/index\.php$ http://%{HTTP_HOST}/ [L,R=301,NS]
 
# .htaccess:
RewriteEngine on
RewriteRule ^index\.php$ http://%{HTTP_HOST}/ [L,R=301,NS]

Open in new window

Avatar of RegProctor

ASKER

no, in .htaccess. I use the same file for the production server (a web hosting company server), my development server & outside access to my clients of my staging server. The the last two cases is the same server and DB, just a different Virtually hosted URLs with different PHP code (one URL accessible only locally for me and the other from the web.)

That's very close but if I add a query string it still removes the index.php. In the case of an existing query string the file name should remain so you don't get something like:

/host/?a=b
ASKER CERTIFIED SOLUTION
Avatar of caterham_www
caterham_www
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Works like a charm  - thanks!

What through me was when I did

RewriteRule .* ${HTTP_HOST} [L,R=301]

Apache through up the system's file path instead of the host name. You showed that you needed to add http:// in front of it. I didn't think of that as it just looked like it was completely ignoring the HTTP_HOST instruction. By the way, do you know why it would do that?
You used ${... while the variable needs to be referenced via %{..., that's why nothing happened.
Sorry, typo, it was a %{... not a ${... you'll see it correct at the top. However, it's not that nothing happened, that's easy, it's that I got the file path, like... /home/name/www/... when I was expecting a URL.