【问题标题】:mod_rewrite - .htaccess help neededmod_rewrite - .htaccess 需要帮助
【发布时间】:2017-09-21 05:33:39
【问题描述】:

我正在尝试配置 .htaccess 文件以执行以下操作:

  1. 如果没有索引文件,则阻止目录列表
  2. 重写所有请求以转到 https
  3. 剥离 www 并重新路由到 https://example.com
  4. 从文件中删除 .php 扩展名:
    a) https://example.com/contact 应该在内部路由到 https://example.com/contact.php
    b) https://example.com/phpfile/1234 应该在内部路由到 https://example.com/phpfile.php?id=1234
    c)我还需要一种方法来重新路由某些具有 2 个甚至 3 个变量的页面,例如: https://example.com/otherphpfile.php?param1=101&param2=xxxx

这是我目前所拥有的:

Options -Indexes
RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule (.*) https://example.com%{REQUEST_URI} [L,R=301,NC]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [QSA,L]

我介绍了 1、2、3、4a... 需要一种优雅的方式来处理 4b 和 4c,它不绑定到特定的文件/路径。它需要处理任何可以接受 1 个或多个参数的 php 文件。

非常感谢任何帮助。

【问题讨论】:

  • 您可以查看此链接:generateit.net/mod-rewrite/index.php
  • 4b。 RewriteRule ^(.*?)/(.*?)/?$ https://example.com/$1.php?id=$2 [L,R=301,NC]应该做吗?
  • 最好将 /otherphpfile/101/xxxx/otherphpfile/101/xxxx/yyyy 路由到 /otherphpfile.php 而不使用任何 GET 参数,并让您的 PHP 代码解析 REQUEST_URI

标签: apache .htaccess mod-rewrite


【解决方案1】:

对于 4b,使用 as

RewriteRule ^phpfile/([^/]*)$ /phpfile.php?id=$1 [L]

Example :
Original URL : https://example.com/phpfile.php?id=123
Rewrite URL : https://example.com/phpfile/123

对于 4c,使用 as

RewriteRule ^otherphpfile/([^/]*)/([^/]*)$ /otherphpfile.php?param1=$1&param2=$2 [L]

Example :
Original URL : https://example.com/otherphpfile.php?param1=1234&param2=abcd
Rewrite URL : https://example.com/otherphpfile/1234/abcd

【讨论】:

  • 知道为什么 RewriteRule ^phpfile/([^/]*)$ /phpfile.php?id=$1 [L] 不起作用???我收到“页面未正确重定向”“Firefox 检测到服务器正在以永远不会完成的方式重定向此地址的请求。”
  • RewriteCond %{ENV:HTTPS} !on [NC] 代替:RewriteCond %{HTTPS} off 并检查是否有帮助。