简体   繁体   中英

how to redirect subdomain to subdir with .htaccess without changing URL

There is a domain/subdomain example.com / www.example.com (obviously they both point to /public_html ) and website placed in this dir works perfectly. I've created subdir /public_html/wwwnew , and subdomain wwwnew.example.com . I want this subdomain to point to this subfolder, but I don't want to change URL typed by user ( wwwnew.example.com ). Of course I need to use .htaccess .

My current .htaccess file:

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(wwwnew.)?example.com$
RewriteRule ^(/)?$ wwwnew [L]

RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*) index.php [L]

Currently when I type in wwwnew.example.com URL changes to wwwnew.example.com/wwwnew . I want this /wwwnew to disappear...

Any help?

 RewriteRule ^(/)?$ wwwnew [L] 

If wwwnew is a physical subdirectory (which you say it is) then you should append a trailing slash on the end of the RewriteRule susbtition (and preferably the index document as well). If you don't then mod_dir will append the slash for you (in order to "fix" the URL) and in doing so triggers an external 301 redirect (which you appear to be seeing). Although this would be a redirect to wwwnew.example.com/wwwnew/ (with a trailing slash), not wwwnew.example.com/wwwnew as you've stated in the question.

 RewriteCond %{HTTP_HOST} ^(wwwnew.)?example.com$ 

However, your condition rewrites requests for both the apex domain and the subdomain. In your description you only describe rewriting from the subdomain, not the apex domain (in which you have another site).

So, try the following instead:

RewriteCond %{HTTP_HOST} ^wwwnew\.example\.com
RewriteRule ^$ wwwnew/ [L]

There's no need for (/)? in .htaccess . Although, preferably, you should rewrite directly to the document (ie. index document) that you want to handle this request (otherwise mod_dir must do this for you). For example:

RewriteRule ^$ wwwnew/index.php [L]

You will need to clear your browser cache, as the erroneous redirect to /wwwnew will have been cached by the browser.

UPDATE:

However, the above only rewrites requests for the bare subdomain, without any URL-path (as stated in the question). In order to rewrite any requests for this subdomain (eg. wwwnew.example.com/<something> ) to the subdirectory then you would need to do something like the following instead:

RewriteCond %{HTTP_HOST} ^wwwnew\.example\.com
RewriteRule !^wwwnew/ wwwnew/index.php [L]

This ensures we don't get a rewrite loop.

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