Use htaccess to rewrite subdomain files to a folde

2019-08-19 07:40发布

问题:

I need to rewrite a files on subdomain to files stored in the folder with name of the subdomain. Only files that start with sitemap should be rewritten. So, if the requests look like this:

http://demo.domain.com/sitemap.xml
http://demo.domain.com/sitemap_more.xml
http://test.domain.com/sitemap.xml
http://test.domain.com/sitemap_alpha.xml

These should rewrite to files:

/content/sitemaps/demo/sitemap.xml
/content/sitemaps/demo/sitemap_more.xml
/content/sitemaps/test/sitemap.xml
/content/sitemaps/test/sitemap_alpha.xml

So, subdomain name is used as a folder in the rewrite-to-path. This should be rewriting NOT redirecting. Also, it would be good to have rules that will work with any domain without need to change domain name everytime.

回答1:

You can match the subdomain with a condition, then rewrite it with the rule :

RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.com
RewriteRule ^(.*)$ http://domain.com/content/sitemaps/%1/$1 [L]

Maybe you want to add a filter on .xml

Add :

RewriteCond %{REQUEST_FILENAME} \.xml

Edit

For file beginning with sitemap :

RewriteCond %{REQUEST_FILENAME} sitemap.*\..+$

This will match any string that finish with sitemap. and end. => this is a filename not an inner match of directory.