首页 > 解决方案 > Having trouble with .htaccess and clean URLs, need redirect on entering the "dirty" URL

问题描述

I know there's a million similar questions on stuff like this, but clearly there's much I don't understand because I haven't been able to derive answers or a solution to my (as I understand it) fairly simple question.

Basically, I'm trying to get an old site back up, but want a more professional look to it this time round, which includes cleaning up the URLs. A typical page is as follows (hosted locally at the moment, but will be assigned a domain in next few days):

192.168.0.200/album-reviews.php?albid=22

Using the following code, I have been able to achieve the above example page loading via manually typing 192.168.0.200/album-reviews/22 into the browser:

RewriteRule ^album-reviews/([0-9a-zA-Z]+) album-reviews.php?albid=$1 [NC,L]

However, what I want as well is for when the link is clicked on my site, it directs the user to /album-reviews/22 instead of album-reviews.php?albid=22. The only way to get the clean URL at the moment is to manually type it into the bar, links from my site do not get the clean URL, the code I have been playing around with (and have been unable to get working) based on sources I've found is this:

RewriteCond %{THE_REQUEST} /album-reviews/?(?:\.php)?\?albid=([0-9a-zA-Z]+)
RewriteRule ^ /album-reviews/%1? [L,R]

So if anyone could shed some light on how I get all this working as desired, I'd be grateful, I hope my question has been articulated appropriately.

On a side note, If i wanted to include the post title in the URL too like this:

192.168.0.200/album-reviews.php?albid=22&ptitle=my first post

how would alter any code to make it like this:

192.168.0.200/album-reviews/22/my first post

Thank you.

标签: phpregex.htaccessurl

解决方案


您可以使用:

Options -MultiViews
RewriteEngine on

RewriteCond %{THE_REQUEST} /album-reviews/?(?:\.php)?\?albid=([^\s&]+)&ptitle=([^\s&]+)
RewriteRule ^ album-reviews/%1/%2? [L,R=301]
RewriteCond %{THE_REQUEST} /album-reviews/?(?:\.php)?\?albid=([^\s&]+)
RewriteRule ^ album-reviews/%1? [L,R=301]

RewriteRule ^album-reviews/([^/]+)/?$ album-reviews.php?albid=$1 [NC,L]
RewriteRule ^album-reviews/([^/]+)/([^/]+)/?$ album-reviews.php?albid=$1&ptitle=$2 [NC,L]

推荐阅读