简体   繁体   中英

.htaccess Rewrite URL to directory that is the same as domain

I have a list of domains that all point to the same IP Address and I want to be able to dynamically rewrite the url to go to a folder based on the domain name.

For example, I want coolsite.com/blah.php to point to /coolsite/blah.php .

I have the following in my .htaccess file, but it doesn't work

#Capture the domain without the 'www' or '.com'
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.*)\.com

#if the request hasn't been rewritten to the new folder
RewriteCond %{REQUEST_URI} !^/%1

#Rewrite request so that it inserts that folder in the path
RewriteRule ^(.*)$ /%1/$1 [L]

I know I can just make a bunch of VirtualHost s in my httpd.conf, but there are a ton of domains that I'm using.

Is it even possible to do this with mod_rewrite?

You cannot use %1 on RHS of RewriteCond .

Have your rules like this:

RewriteCond %{HTTP_HOST}::%{REQUEST_URI} ^(?:www\.)?(.+?)\.com::(?!\1).+$
RewriteRule ^(.*)$ /%1/$1 [L]

I finally found my answer here .

As anubhava said, you can't use a backreference in the RHS of RewriteCond but you can use it in the LHS.

My final code is:

RewriteCond %{SERVER_NAME} (?:www\.)?(.+?)\..+$
RewriteCond %1::%{REQUEST_URI} !^(.*?)::/\1/
RewriteRule ^(.*)$ /%1/$1 [L]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM