如何为 GET 请求正确配置 Apache 重写规则?

Posted

技术标签:

【中文标题】如何为 GET 请求正确配置 Apache 重写规则?【英文标题】:How I can configure correctly Apache rewrite rule for GET request? 【发布时间】:2021-05-04 14:34:57 【问题描述】:

我在尝试创建用户友好的 URL 时遇到以下问题,它返回 500 错误。

没用

RewriteEngine On
RewriteRule  ^page/(.+)$   /page.php?type=$1   [L]

只有在我更改脚本名称时才能使用这个

RewriteRule  ^page/(.+)$   /change-page.php?type=$1   [L]

有什么方法可以保留重定向到页面的 page.php 吗?谢谢

这里是完整的 .htaccess 配置

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# For LocalHost !.php
RewriteCond %HTTP_HOST !=localhost
RewriteCond %HTTP_HOST !=127.0.0.1
RewriteCond %REMOTE_ADDR !=127.0.0.1
RewriteCond %REMOTE_ADDR !=::1

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %THE_REQUEST ^[A-Z]3,\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %REQUEST_FILENAME !-d
RewriteCond %REQUEST_FILENAME.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

RewriteRule  ^page/(.+)$  /page.php?type=$1   [L]

【问题讨论】:

您能否检查您的 Apache error.log 文件是否存在 500 错误。同时发布您有问题的完整 .htaccess 感谢您的建议。我正在使用 OpenServer 并检查了 Apache 日志,它只显示 500 - 662 错误。您可以看到完整的 .htaccess 配置。 【参考方案1】:

您应该尝试在 .htaccess 文件中遵循以下规则。请确保在测试您的 URL 之前清除您的浏览器缓存。

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# For LocalHost !.php
RewriteCond %HTTP_HOST !=localhost
RewriteCond %HTTP_HOST !=127.0.0.1
RewriteCond %REMOTE_ADDR !=127.0.0.1
RewriteCond %REMOTE_ADDR !=::1

## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %THE_REQUEST ^[A-Z]3,\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L]


# To internally forward /dir/foo to /dir/foo.php
RewriteCond %REQUEST_FILENAME !-d
RewriteCond %REQUEST_FILENAME.php -f
RewriteRule ^(.*?)/?$ $1.php [L]


RewriteCond %REQUEST_FILENAME !-f
RewriteCond %REQUEST_FILENAME !-d
RewriteRule ^page/([\w-]+)/?$ page.php?type=$1 [L,NC]

【讨论】:

【参考方案2】:

试试这些规则:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /

# For LocalHost !.php
RewriteCond %HTTP_HOST !=localhost
RewriteCond %HTTP_HOST !=127.0.0.1
RewriteCond %REMOTE_ADDR !=127.0.0.1
RewriteCond %REMOTE_ADDR !=::1
## hide .php extension
# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %THE_REQUEST ^[A-Z]3,\s([^.]+)\.php[?\s] [NC]
RewriteRule ^ %1 [R=301,L]

RewriteCond %REQUEST_FILENAME !-f
RewriteCond %REQUEST_FILENAME !-d
RewriteRule ^page/([\w-]+)/?$ page.php?type=$1 [L,QSA,NC]

# To internally forward /dir/foo to /dir/foo.php
RewriteCond %REQUEST_FILENAME !-d
RewriteCond %DOCUMENT_ROOT/$1.php -f
RewriteRule ^(.*?)/?$ $1.php [L]

【讨论】:

以上是关于如何为 GET 请求正确配置 Apache 重写规则?的主要内容,如果未能解决你的问题,请参考以下文章

IIS 7 权限:如何为目录设置正确的权限?

如何为容器设置正确的cpu millicores?

如何为带有可选 URL 参数的 GET 请求映射不同的 JSON 响应

XAMPP:如何为 PHP 配置 Apache

如何为这种请求创建正确的 NSPredicate?

如何为多个并发事务请求正确处理 JPA ObjectOptimisticLockException?