【问题标题】:remove id and index.php via htaccess in subdirectory通过子目录中的 htaccess 删除 id 和 index.php
【发布时间】:2016-02-04 16:41:16
【问题描述】:

当前网址:

domain/index.php?id=p123

我想要:

  1. 添加www
  2. 删除:index.php
  3. 删除“id”表单网址

我是这样做的:

RewriteCond %{THE_REQUEST} /(?:index\.php)?\?id=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=302,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?id=$1 [L]

RewriteCond %{THE_REQUEST} /(?:index\.php)?\?id=([^\s&]+) [NC]
RewriteRule ^ /%1? [R=302,L,NE]


RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,NE,L]

RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

如果 domian 没有子目录,它可以工作。

如何更改此代码以支持子目录,如下所示:

domian/subdirectory/index.php?id=p123

【问题讨论】:

    标签: .htaccess mod-rewrite url-rewriting url-redirection friendly-url


    【解决方案1】:

    我会这样处理:

    首先,将非 www 的 URL 重定向到 www 的 URL:

    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTPS}s ^on(s)|
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    

    将友好 URL 重写为相应的 index.php 文件:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*/)?([^/]+)$ /$1index.php?id=$2 [L]
    

    接下来,处理包含 index.php 的原始 URI:

    RewriteCond %{THE_REQUEST} ^GET\ /(.*/)?(?:index\.php)?\?id=([^\s&]+) [NC]
    RewriteRule ^ /%1%2? [R=301,L]
    

    最后一条规则也将处理像 domain.com/dir/?id=sthdomain.com/dir/index.php?id=sth 这样的 URL

    【讨论】:

      【解决方案2】:

      您可以通过以下更改来完成此操作:

      RewriteCond %{THE_REQUEST} \ /(.*/|)(?:index\.php)?\?id=([^\s&]+) [NC]
      RewriteRule ^ /%1%2? [R=302,L,NE]
      
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{REQUEST_URI} !index\.php
      RewriteRule ^(.*/|)([^/]*)$ $1index.php?id=$2 [L]
      

      我们知道%{THE_REQUEST} 的格式为GET /path/to/index.php?id=12312412 HTTP/1.1 或类似的格式。在第一条规则中,我们匹配\,这是一个文字空格,然后是始终存在的开始斜线。 (.*/|) 将匹配 index.php 之前的所有内容,或者完全不匹配。我们在第二条规则中做的同样的把戏。我添加了RewriteCond %{REQUEST_URI} !index\.php 以防止特定目录的 index.php 不存在时出现无限循环。

      【讨论】:

      • 嘿,和我的答案很相似^_^。虽然我领先你一分钟;-)
      • @hjpotter92 但我的答案包含两个额外的|,而您的答案没有。所以:哈,开你的玩笑,我赢了! ;-)
      猜你喜欢
      • 2011-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-31
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多