我怎样才能在 .htaccess 中有 2 个参数?

问题描述 投票:0回答:1

我有一个PHP文件:

example.com/products/index.php

我的目标是能够做到这一点:

example.com/products/186/Hello to you

在 PHP 中我可以做

$_GET['id']
这将是
186
,

$_GET['cat']
这将是“你好”。

到目前为止,我在下面尝试了这个,但我得到:

您无权访问此资源。 此外,尝试使用 ErrorDocument 时遇到 403 Forbidden 错误

Options -MultiViews

RewriteEngine On

# HTTP to HTTPS canonical redirect
RewriteCond %{HTTP_HOST} example\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule (.*) https://example.com/$1 [R=301,L]

# Abort early if the request already maps to (or looks like) a file or directory
RewriteCond %{REQUEST_URI} \.\w{2,4}$ [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]

RewriteRule ^(products)/([^/]*)/?(.*) $1/index.php?id=$2&cat=$3 [L]

# 3. Extensionless URLs for other requests  (this below works fine and is for something else)
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule (.*) $1.php [L]

php .htaccess mod-rewrite
1个回答
0
投票

您的“403 Forbidden”问题与 Apache 的最新更新以及您请求的 URL 中的spaces有关。如以下问题所述:

RewriteRule ^(products)/([^/]*)/?(.*) $1/index.php?id=$2&cat=$3 [L]

由于您允许在请求的 URL 中使用 spaces(在请求中编码为

%20
),因此您需要包含
B
标志以便对反向引用进行 URL 编码。但是,您的正则表达式似乎过于“灵活”,因为它使第三个路径段成为可选的(即接受
/products/anything
形式的 URL)——这是故意的吗?

请尝试以下操作:

RewriteRule ^(products)/([^/]*)/?(.*) $1/index.php?id=$2&cat=$3 [B,L]
© www.soinside.com 2019 - 2024. All rights reserved.