【问题标题】:.htaccess rewrite: subdomain as GET var and path as GET var.htaccess 重写:子域为 GET var,路径为 GET var
【发布时间】:2013-08-18 21:29:44
【问题描述】:

想要的结果:

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

【问题讨论】:

标签: php apache .htaccess mod-rewrite


【解决方案1】:

使用第一条规则添加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标志,否则第一条规则的查询字符串会丢失。

【讨论】:

  • 啊,'查询字符串追加',有趣!非常有用,谢谢。
  • 嗨 Jon Lin 如何重写 admin.example.com -> example.com/admin
  • 上面的代码似乎不适用于 OP 的最后一个示例 (hello.example.com/world/test)。它将在 'path=' var as '/world/test/test' 中重复第二段 (/test) 两次。
  • 第一条规则将创建一个无限循环,因为 htaccess 在每条规则之后都会重新启动,并且它在条件中找到的子域仍然存在。为了使其正常工作,您需要添加一个条件来测试规则是否已将子域放入查询字符串中。示例:RewriteCond %{QUERY_STRING} !^(.*)path=?(.*)$
  • 第一个规则没有 L 标志,第二个规则被应用并结束循环
猜你喜欢
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
  • 2014-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多