php - .htaccess 重写 : subdomain as GET var and path as GET var

标签 php apache .htaccess mod-rewrite

期望的结果:

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,我可以实现一个或另一个重新映射,但不能同时实现这两个。

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] 

我很难将两者结合起来......有什么建议吗?

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

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

最佳答案

使用第一条规则添加subdomain参数,不改变URI,然后使用第二条规则将URI路由到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标志,否则第一条规则的查询字符串会丢失。

关于php - .htaccess 重写 : subdomain as GET var and path as GET var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18303858/

相关文章:

php - 如何通过 SQL 在 PHP 中创建动态表

php - 扩展已实例化但没有 'new' 的类

php - .htaccess 所有目录均给出 403 Forbidden

php - 禁止直接访问某个页面

javascript - 对elFinder和CKeditor整合直接上传文件

php - Wordpress Ajax 用于搜索结果 - 查询仅返回 1 个结果

php - 没有管理员权限的XAMPP服务

Wordpress 和 angular2 url 路由不起作用

apache - reducer 卡在16%

apache - RewriteRule 将 url 部分作为参数传递给 php 脚本