开发者

Dynamic URL rewriting using .htaccess

开发者 https://www.devze.com 2023-01-30 04:05 出处:网络
I\'m having some trouble with rewriting dynamic URLs using .htaccess. The rewrite should be fairly simple,开发者_StackOverflow中文版 but I\'m missing something and would greatly appreciate a hand.

I'm having some trouble with rewriting dynamic URLs using .htaccess. The rewrite should be fairly simple,开发者_StackOverflow中文版 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]


Your page assets are not loading because the URLs for them are being rewritten also.

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 %{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.

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 word feed in the URL, then you could try something like this (but use the !-f and !-d condtions there too):

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]
0

精彩评论

暂无评论...
验证码 换一张
取 消