【问题标题】:How to set a .htaccess custom rewrite?如何设置 .htaccess 自定义重写?
【发布时间】:2025-11-27 09:35:01
【问题描述】:

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

pageurl/profile/username

代替

pageurl/profile/?username=username

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

谢谢!

【问题讨论】:

  • 是否可以说您已设置虚拟主机以使用.htaccess 并且已安装mod_rewrite?到目前为止,您尝试过什么?

标签: php html apache mod-rewrite


【解决方案1】:

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

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

这适用于 文档根目录 的 .htaccess 文件中(不在子文件夹中) - 如果您要将其添加到 httpd 中的 <VirtualHost>,规则会略有不同例如 -vhosts.conf。


由于您实际上有一个名为 /profile 的目录,但是您可能会遇到一个终端循环,其中 /profile 重定向到 /profile 重定向到 /profile 无限。

为避免这种情况,您需要 not filenot directory 条件:

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

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

【讨论】:

  • 所以我将它添加到我的 htaccess 中,只是它不起作用我希望我的 url 像这个配置文件/alex alex 是用户名。
  • 在没有 pageurl 的情况下试一试...我不能 100% 确定您是否将其作为样板保留。哦,您的 .htaccess 需要位于文档根目录中 - 而不是任何子文件夹。
  • 我添加了地图结构的截图。
  • 是的,您的 hrefs 将采用 <a href="/profile/alex">Alex's Profile</a> 或类似的形式...从屏幕截图中,您的 docroot 看起来好像是 /public 目录,所以您的 .htaccess 是在正确的地方。
  • ...不过,您可能会遇到一个问题,即有一个名为profile 的实际目录,因为profile/index.php 将路由到profile/index.php?username=index.php,而profile/index.php?username=index.php 将循环到profile/index.php?username=index.php等等......永远,我会更新答案以考虑到这一点。
最近更新 更多