使用 .htaccess 动态 URL 重写
我在使用 .htaccess 重写动态 URL 时遇到一些问题。重写应该相当简单,但我遗漏了一些东西,非常感谢您的帮助。
URL 方案:
http://www.example.com/index.php?p=/category/page-slug
应该翻译为:
http://www.example.com/category/page-slug
并且
http://www.example.com/index.php?p=/category/&f=feed/rss
应该变成:
http://www.example.com/category/feed/rss
我当前的重写规则是:
RewriteRule ^(.+)?$ index.php?p=$1 [NC,L]
但这并没有按预期工作。有什么建议吗?
编辑: 该规则现在在加载页面时部分起作用,但没有显示任何页面资源(例如我的样式表和图像)。我猜这是因为它们是相对路径。关于解决方法有什么想法吗?
RewriteRule ^([a-zA-Z0-9-/+]+)$ http://example.com/index.php?p=/$1 [L]
I'm having some trouble with rewriting dynamic URLs using .htaccess. The rewrite should be fairly simple, but I'm missing something and would greatly appreciate a hand.
The URL scheme:
http://www.example.com/index.php?p=/category/page-slug
should translate to:
http://www.example.com/category/page-slug
And
http://www.example.com/index.php?p=/category/&f=feed/rss
should become:
http://www.example.com/category/feed/rss
My current rewrite rule is:
RewriteRule ^(.+)?$ index.php?p=$1 [NC,L]
but that isn't working as it should. Any suggestions?
Edit:
This rule is now partially working as it loads the page, but none of the page assets like my stylesheets and images are showing. I'm guessing it's because they are relative paths. Any ideas on a workaround?
RewriteRule ^([a-zA-Z0-9-/+]+)$ http://example.com/index.php?p=/$1 [L]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的页面资源未加载,因为它们的 URL 也被重写。
例如,像
请求这样
的规则将被重写为
避免这种情况的常见方法是防止对真实文件的请求与规则匹配。这通常是通过将这两个 RewriteCond 语句放在规则之上来完成的:
!-f
表示不是文件,!-d
表示不是目录。然后,您需要一个不同的规则来将 URL 与其中的
f=
进行匹配。 lolraccoon 的答案有一个很好的建议,但我认为他的建议与你想要的相反。您的规则如何知道何时需要
f=
参数?如果它是基于 URL 中存在feed
一词,那么您可以尝试类似的操作(但使用!-f
和!-d< /code> 条件也有):
Your page assets are not loading because the URLs for them are being rewritten also.
For instance, with a rule like
a request for
will be rewritten to
A common way to avoid this is to prevent requests for real files from matching the rule. This is usually done by putting these two RewriteCond statements above your rule:
The
!-f
means not a file and!-d
means not a directory.Then you'll need a different rule to match the URL with the
f=
in it. The answer from lolraccoon has a good suggestion, but I think he has it reversed from how you want it.How will your rule know when the
f=
parameter is needed? If it's based on the presence of the wordfeed
in the URL, then you could try something like this (but use the!-f
and!-d
condtions there too):请尝试以下操作:
Try the following: