user2915702
user2915702

Reputation:

Redirecting subdirectory to subdomain in .htaccess

I want to redirect a subdirectory to a subdomain using .htaccess. My current code:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP_HOST} ^(www.)?sub.example.com$
RewriteRule ^(/)?$ subdirectory [L]
</IfModule>

This code redirects to sub.example.com/subdirectory. How do I remove /subdirectory from the new URL?

Upvotes: 1

Views: 3130

Answers (1)

anubhava
anubhava

Reputation: 786041

Place this rule on top, before all other rules:

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^subdirectory/(.*)$ http://www.sub.example.com/$1 [L,NC,R=301]

Complete .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule ^subdirectory/(.*)$ http://sub.example.com/$1 [L,NC,R=301]

RewriteCond %{HTTP_HOST} ^(www\.)?sub\.example\.com$ [NC]
RewriteCond %{REQUEST_URI} !(jpe?g|gif|bmp|png|tiff|css|js)$ [NC]
RewriteRule !subdirectory subdirectory%{REQUEST_URI} [NC,L]

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Upvotes: 2

Related Questions