如何设置 .htaccess 自定义重写?

How to set a .htaccess custom rewrite?

我目前正在努力实现这个目标:

pageurl/profile/username

而不是

pageurl/profile/?username=username

我怎样才能以正确的方式做到这一点?我在谷歌上搜索了很长时间以找到正确的方法,但当我尝试以我想要的方式编辑它时,对我没有任何用处。

谢谢!

假设用户名是用户名而不是字符串 "username" - 我已经删除了 pageurl 部分,因为它看起来像样板文件。

RewriteEngine On
RewriteRule ^profile/([^/]+)/?$ /profile/?username= [L]

这是针对 文档根目录 中的 .htaccess 文件(不在子文件夹中)- 如果将其添加到<VirtualHost> 在 httpd-vhosts.conf 例如。


因为您实际上有一个名为 /profile 的目录,所以您可能会遇到终端循环,其中 /profile 重定向到 /profile 重定向到 /profile无穷无尽。

为避免这种情况,您需要不是文件不是目录 条件:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^profile/([^/]+)/?$ /profile/?username= [L]

这将阻止像 /profile/index.php 这样的 URL 重定向到 /profiles/?username=index.php,因为请求必须既不是文件也不是目录。