.htaccess port rewrite for subdomains

Viewed 87

I am trying to redirect all SUBDOMAINS, except portal.example.com from any port (usually it's 80 or 443) to port 30000.

e.g.

  • example.com: (any port) shall have no change
  • www.example.com: (any port) shall have no change
  • portal.example.com (any port) shall have no change
  • a.example.com (any port) shall be updated to a.example.com:30000
  • b.example.com (any port) shall be updated to b.example.com:30000
  • *.example.com (any port) shall be updated to *.example.com:30000
  • etc.

I currently have following .htaccess, directing example.com and *.example.com without change:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
2 Answers

Could you please try following, written as per your shown samples. Please make sure you clear your browser cache before testing URLs.

RewriteEngine ON
RewriteCond !^example\.com [NC]
RewriteCond !^www\.example\.com [NC]
RewriteCond !^portal\.example\.com [NC]
RewriteCond (.*example\.com) [NC]
RewriteCond %{SERVER_PORT} !^30000$
RewriteRule ^(.*)$ http://%{HTTP_HOST}:30000%{REQUEST_URI} [R=301,NE,L]

A bit refactored rule:

RewriteEngine On

RewriteCond %{SERVER_PORT} !=30000
RewriteCond !^((?:www|portal)\.)?example\.com [NC]
RewriteRule ^ http://%{HTTP_HOST}:30000%{REQUEST_URI} [R=301,NE,L]
Related