大网数据广告活动
网站运营与故障问答

Is there a way to set up a redirect in htaccess to convert a folder/paths to a params

· 52CE 我爱测

After trawling through posts I have this RewriteCond %{HTTP_HOST} ^example.software$ RewriteRule ^downloads$ https://example.software\?mode\=downloads&%{QUERY_STRING} [R=302,L] This works fine to convert example.software/download…

问题原文

原帖链接 · Rohit Gupta · CC BY-SA 4.0

After trawling through posts I have this

RewriteCond %{HTTP_HOST} ^example.software$
RewriteRule ^downloads$ https://example.software\?mode\=downloads&%{QUERY_STRING}  [R=302,L]

This works fine to convert

example.software/downloads?name=bing

to

example.software?mode=downloads&name=bing

And I could make that work, but what I really want is to convert

example.software/downloads/bing

to

example.software?mode=downloads&name=bing    

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

RewriteCond %{HTTP_HOST} ^example.software$
RewriteRule ^downloads$ https://example.software\?mode\=downloads&%{QUERY_STRING}  [R=302,L]

This is an external redirect. The URL is changed to /?mode=downloads&name=bing - which is what the user will see. The idea of implementing a "friendly" URL like /downloads/bing is so this is the only URL that the user sees and the underlying file path that actually handles the request is hidden from the user. If you are going to "redirect" the request to the "ugly" URL (the file path that handles the request) then there is not much point in implementing the "friendly" URL to begin with (except maybe for "sharing").

(You are also unnecessarily backslash-escaping ? and = in the substitution string - this is an "ordinary" string, not a regex. There should also be a slash after the hostname if you are redirecting.)

I'm assuming that the file that actually handles the request is index.php in the document root.

Try the following instead:

RewriteCond %{HTTP_HOST} ^example.software$
RewriteRule ^(downloads)/([^/]+)$ index.php?mode=$1&name=$2 [L]

This internally rewrites (the URL in the browser does not change) a request for example.software/downloads/bing to /index.php?mode=downloads&name=bing.

$1 and $2 are backreferences to the first and second capturing groups in the RewriteRule pattern. $1 is always downloads, but $2 is whatever is in the second path segment.

The URL in the browser's address bar remains as /downloads/bing, but your index.php script is called with the mode and name URL (GET) parameters.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2021-10-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。