htaccess for subdomain and url rewrite

2019-08-31 00:49发布

问题:

I'm in trouble with this .htaccess

RewriteCond %{HTTP_HOST} appname.domain.com
RewriteCond %{REQUEST_URI} !appname/
RewriteRule ^(.*)$ /appname/$1 [L]

In the document root (not really the root document, let's say a v-domain folder) i have this folder called 'appname'. On appname.domain.com everything shows up fine as it should. Now my problem is when I want to do something like this

http://appname.domain.com/somefolder

I don't want the url to be rewritten to appname.domain.com/appname/somefolder In the url bar. Any help?

Update: In the document root i have

RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$ [NC]
RewriteCond %{REQUEST_URI} !^v-domain/
RewriteRule ^(.*)$  /v-domain/$1 [L]

In v-domain

RewriteEngine On
RewriteBase /v-domain/

RewriteCond %{HTTP_HOST} appname.domain.com
RewriteCond %{REQUEST_URI} !appname/
RewriteRule ^(.*)$ /appname/$1 [L]
RewriteCond %{HTTP_HOST} appname.domain.com
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^appname/(.+)$ http://appname.domain.com/$1/    [R=301,L]
###################
RewriteCond %{HTTP_HOST} appname2.domain.com
RewriteCond %{REQUEST_URI} !appname2/
RewriteRule ^(.*)$ /appname2/$1 [L]
RewriteCond %{HTTP_HOST} appname2.domain.com
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^appname2/(.+)$ http://appname2.domain.com/$1/  [R=301,L]

回答1:

Try to make a dir in your subdomain folder with an index in it and then try to reach that path. You will see the url being rewritten in the ugly mentioned way "appname.domain.com/appname/somefolder"

That sounds like it's mod_dir's DirectorySlash interferring. With DirectorySlash turned on, if mod_dir sees that a request is made for a directory and is missing the trailing slash, it redirects the browser to the equivalent URL to include the trailing slash.

Something you can do is to turn DirectorySlash off but there's a disclosure concern when it comes to DirectoryIndex'ing (see the DirectorySlash entry in mod_dir). You could try adding some rules to do this redirect for you but make sure to redirect without the /appname/ bit in the URL:

RewriteCond %{HTTP_HOST} appname.domain.com
RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^appname/(.+)$ http://appname.domain.com/$1/    [R=301,L]

This basically checks if the request is for the host appname.domain.com, that the requested entity is a directory, that the request does not end with a trailing slash, and if the request has already been rewritten for /appname/ redirect the browser to the same URL (without appname) but with a trailing slash. After the redirect, the first rule that you have will internally rewrite the URI to include the /appname/, but since the request now ends with a trailing slash, mod_dir should ignore it.