.htaccess rewrite: subdomain as GET parameter and

2019-07-21 03:45发布

I want to use htaccess to rewrite subdomains to a get paramater but keep everything after the domain intact + adding the parameter to the end or the url.

Desired result:

http://mpmain.example.com/          -> index.php
http://www.example.com/             -> index.php
http://hello.example.com/           -> index.php?subdomain=hello
http://whatever.example.com/        -> index.php?subdomain=whatever
http://whatever.example.com/index.php?page=login -> index.php?page=login&subdomain=whatever
http://whatever.example.com/index.php?page=about&action=help -> index.php?page=about&action=help&subdomain=whatever

With the .htaccess I have right now, I can achieve the subdomain to parameter (index.php?subdomain=whatever) mapping with the following code.

RewriteEngine On

# Parse the subdomain as a variable we can access in PHP, and
# run the main index.php script
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{HTTP_HOST}        !^www
RewriteCond %{HTTP_HOST}        !^mpmain
RewriteCond %{HTTP_HOST}         ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^(.*)$ /$1?subdomain=%1

Added a second rewrite below but this one does not work. How can i adjust it so i get the desired results?

# Map all requests to the 'path' get variable in index.php
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?subdomain=$1 [L,QSA]

I took the code from .htaccess rewrite: subdomain as GET var and path as GET var

1条回答
走好不送
2楼-- · 2019-07-21 04:12

You can use this code in your root .htaccess:

DirectoryIndex index.php
RewriteEngine On

# Parse the subdomain as a variable we can access in PHP, and
# run the main index.php script    
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{HTTP_HOST} !^(?:www|mpmain) [NC]
RewriteCond %{HTTP_HOST} ^([^.]+)\.[^.]+\.[^.]+$
RewriteRule ^(.*)$ $1?subdomain=%1 [L,QSA]
查看更多
登录 后发表回答