简体   繁体   中英

Rewrite subdomain to a folder and redirect that folder to a subdomain

I have rewrite rule that sends all users from random.example.com to /random/

But I want to make it so that IF a user was to directly visit /random/ it would redirect (redirect NOT rewrite) them to the subdomain.

This is what I have:

RewriteEngine on  
# NO WWW
RewriteCond %{HTTP_HOST} ^www.example.com [NC] 
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

# USE RANDOM SUB DOMAIN WITH CONTENT IN SUB FOLDER
RewriteCond %{HTTP_HOST} random.example.com$
RewriteCond %{REQUEST_URI} !^/random
RewriteRule ^(.*)$ /random/$1 [L]

# SEND SNOOPERS AT SUB FOLDER TO SUB
Redirect ^(.*)$/random/$1 %{HTTP_HOST}random.example.com$

However, I get a server 500 error for that last line. Basically it needs to handle any urls that come through on the random directory, so for example:

http://example.com/random -> http://random.example.com/

http://example.com/random/fakeplace/ -> http://random.example.com/fakeplace/

http://example.com/random?id=4 -> http://random.example.com/?id=4

Your syntax is wrong with the last line. You are even mixing RewriteRule with Redirect. Try these rules. I changed a few things.

RewriteEngine on  
# NO WWW
RewriteCond %{HTTP_HOST} ^www.example.com [NC] 
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

# USE RANDOM SUB DOMAIN WITH CONTENT IN SUB FOLDER
RewriteCond %{HTTP_HOST} ^random\.example\.com$
RewriteRule !^random/? random%{REQUEST_URI} [NC,L]

RewriteCond %{THE_REQUEST} \s/random/([^\s]*) [NC]
RewriteRule ^ http://random.example.com/%1 [R=301,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