在.htaccess中为不同变量重写URL

9rbhqvlz  于 2022-11-16  发布在  其他
关注(0)|答案(2)|浏览(168)

我试图重写我的网站的URL为PHP页面我有不同的条件

first example.com/view.php?id=1

在这里我需要从URL隐藏ID我需要它像这样

example.com/view/1

第二,对于某些页面,我有不同变量,如下面的示例所示

example.com/view/book.php?id=1&user=33333&booked=1

我需要重写这个例子的链接

example.com/view/book/1/33333/1

下面是我在.htaccess页面中所做操作

# Remove .php file extension on requests
RewriteRule ^(.+).php$ /$1 [R,L]

RewriteRule ^(view/booked)/([0-9]*)$ $1.php?id=$2 [END]

# Append .php extension for other requests
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^(.*?)/?$ /$1.php [END]

RewriteRule ^(view/book)/([0-9]*)/([0-9]*)/([0-9]*)$ $1.php?id=$2&user=$3&booked=$4 [END]

例如,它运行良好,没有任何问题,对于example.com/view/booked/1也是如此。
第二个例子的唯一问题是example.com/view/book.php?id=1&user=33333&booked=1我需要隐藏变量

yquaqz18

yquaqz181#

请尝试使用显示的示例遵循以下.htaccess规则。

请确保:

  • 在测试URL之前清除浏览器缓存。
  • 请确保.htaccess文件与view文件夹和view.php位于同一根文件夹中。
RewriteEngine ON

##Redirect from example.com/view.php?id=1 To example.com/view/1 rules.
RewriteCond %{THE_REQUEST} \s/([^.]*)\.php\?id=(\d+)\s [NC]
RewriteRule ^ /%1/%2? [R=301,L]

##Internal handling to rewrite to view.php file.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/?$ $1.php?id=$2 [QSA,L]

##Redirect from example.com/view/book.php?id=1&user=33333&booked=1 TO example.com/view/book/1/33333/1
RewriteCond %{THE_REQUEST} \s/(view)/([^.]*)\.php\?id=(\d+)&user=(\d+)&booked=(\d+)\s [NC]
RewriteRule ^ /%1/%2/%3/%4/%5? [R=301,L]

##Internal handling to rewrite to book.php file.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)?$ $1/$2.php?id=$3&user=$4&booked=$5 [QSA,L]
hxzsmxv2

hxzsmxv22#

我建议你保持事情的清晰和精确。这可能是你正在寻找的:

RewriteEngine on

# redirect /view/book.php?id=1&user=33333&booked=1 => /view/book/1/33333/1
RewriteCond %{QUERY_STRING} ^id=(\d+)&user(\d+)&booked=(\d+)$
RewriteRule ^/?view/book\.php$ /view/book/%1/%2/%3 [R=301,END]

# redirect /view.php?id=1 => /view/1
RewriteCond %{QUERY_STRING} ^id=(\d+)$
RewriteRule ^/?view\.php$ /view/%1 [R=301,END]

# rewrite /view/1 => /view.php?id=1
RewriteRule ^/?view/(\d+)$ /view.php?id=$1 [END]

# rewrite /view/book/1/33333/1 => /view/book.php?id=1&user=33333&booked=1
RewriteRule ^/?view/book/(\d+)/(\d+)/(\d+)$ /view/book.php?id=$1&user=$2&booked=$3 [END]

# rewrite to php files, if those exist
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^ %{REQUEST_FILENAME}.php [END]

首先使用R=302temporary 重定向可能是有意义的。只有当一切都按预期运行时,才将其更改为R=301permanent 重定向。这可以防止客户端出现令人讨厌的缓存问题。此外,您总是希望使用一个新的匿名浏览器窗口进行测试。
执行这些规则的最佳位置是中央http服务器的主机配置。如果您无法访问该配置,可以使用 * 分布式 * 配置文件(.htaccess),* 如果您在http服务器中启用了对这些文件的考虑 * ...如果该文件位于http主机的DOCUMENT_ROOT文件夹中,上述规则同样适用。

相关问题