.htaccess 重写:子域为 GET var,路径为 GET var [英] .htaccess rewrite: subdomain as GET var and path as GET var

查看:28
本文介绍了.htaccess 重写:子域为 GET var,路径为 GET var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想要的结果:

http://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://example.com/world            -> index.php?path=world
http://example.com/world/test       -> index.php?path=world/test
http://hello.example.com/world/test -> index.php?subdomain=hello&path=world/test

使用我现在拥有的 .htaccess,我可以实现一个或另一个重新映射,但不能同时实现.

With the .htaccess I have right now, I can achieve one or the other re-mapping, but not both at the same time.

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}         ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^.*$ index.php?subdomain=%1

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

我很难将两者结合起来...请指点一下?

I'm having a hard time combining the two...any pointers, please?

编辑
我现在遇到的不需要的行为是,如果我有一个子域和 .com/之后的路径,则只会传递子域,即:

EDIT
The unwanted behavior I'm experiencing now is that if I have a subdomain and a path after .com/, only the subdomain will be passed through, ie:

http://hello.example.com/world-> index.php?subdomain=hello

推荐答案

使用第一条规则添加subdomain参数,不改变URI,然后使用第二条规则将URI路由到<代码>index.php:

Use the first rule to add the subdomain parameter, without changing the URI, then use the 2nd rule to route the URI to 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} !-f
RewriteCond %{HTTP_HOST}        !^www
RewriteCond %{HTTP_HOST}         ^([^\.]+)\.([^\.]+)\.([^\.]+)$
RewriteRule ^(.*)$ /$1?subdomain=%1

# 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?path=$1 [L,QSA] 

第二条规则需要QSA标志,否则第一条规则的查询字符串会丢失.

The second rule needs to have the QSA flag, otherwise the first rule's query string gets lost.

这篇关于.htaccess 重写:子域为 GET var,路径为 GET var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆