简体   繁体   English

使用.htaccess进行动态URL重写

[英]Dynamic URL rewriting using .htaccess

I'm having some trouble with rewriting dynamic URLs using .htaccess. 我在使用.htaccess重写动态URL时遇到了一些麻烦。 The rewrite should be fairly simple, but I'm missing something and would greatly appreciate a hand. 重写应该相当简单,但是我缺少了一些东西,将不胜感激。

The URL scheme: URL方案:

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]

Your page assets are not loading because the URLs for them are being rewritten also. 您的页面资产未加载,因为它们的URL也正在被重写。

For instance, with a rule like 例如,使用类似

RewriteRule ^(.*)$ index.php?p=$1 [NC,L]

a request for 要求

http://www.example.com/images/logo.gif

will be rewritten to 将被重写为

http://www.example.com/index.php?p=/images/logo.gif

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: 通常通过将这两个RewriteCond语句放在规则上方来完成此操作:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?p=$1 [NC,L]

The !-f means not a file and !-d means not a directory. !-f表示不是文件, !-d表示不是目录。

Then you'll need a different rule to match the URL with the f= in it. 然后,您将需要一个不同的规则来将URL与其中的f=匹配。 The answer from lolraccoon has a good suggestion, but I think he has it reversed from how you want it. lolraccoon的答案有一个很好的建议,但我认为他将它与您想要的相反。

How will your rule know when the f= parameter is needed? 您的规则如何知道何时需要f=参数? If it's based on the presence of the word feed in the URL, then you could try something like this (but use the !-f and !-d condtions there too): 如果它基于URL中的单词feed ,那么您可以尝试这样的操作(但也可以使用!-f!-d条件):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*/)(feed.*)$ index.php?p=/$1&f=$2

Try the following: 请尝试以下操作:

RewriteRule ^index.php?p=(.*)&f=(.*)$ /$1$2 [NC,L]
RewriteRule ^index.php?p=(.*)$ /$1 [NC,L]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM