PDA

View Full Version : Help with regular expressions



bot
04-11-2011, 07:18 PM
Currently, to view a webpage on my website, the user must go to http://mywebsite.com/articleviewer.php?id=mypage (not my actual domain :p). What I want is a RewriteRule in my .htaccess file that replaces http://mywebsite.com/mypage with http://mywebsite.com/articleviewer.php?id=mypage (mypage being replaced with the page ID). Is there a set of regular expressions to do this? I found an example online, but it only replaces numbers, not strings.

kahawai chaser
04-11-2011, 07:42 PM
You mean a redirect? I have read the 301 is the preferred method for search engines, in that you don't dilute or lose any rankings in search results. Procedure here. (http://www.isitebuild.com/301-redirect.htm) Then I think you need specify to Google the canonical or preferred version (http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html) of your url for duplicate content - this I believe reduces the spread of any page rank across similar url's. Might pay to sign up to webmaster tools, (https://accounts.google.com/ServiceLogin?service=sitemaps&passive=1209600&continue=https://www.google.com/webmasters/tools/&followup=https://www.google.com/webmasters/tools/) where Google have recently added a section for URL's in the diagnostic section and how they might assign a preferred url (http://www.google.com/support/webmasters/bin/answer.py?answer=139394) if not already specified by the webmaster.

bot
05-11-2011, 05:21 PM
Got it working -- perhaps Erayd could check this over?

RewriteRule ^([A-Za-z0-9]+)/?$ somepage.php?id=$1

What this does is, when the user goes to http://mywebsite.com/home, it's really going to http://mywebsite.com/somepage.php?id=home.

Erayd
05-11-2011, 05:39 PM
You mean a redirect?Nope, he means URL rewriting - it's not the same thing.


Got it working -- perhaps Erayd could check this over?Sure.


RewriteRule ^([A-Za-z0-9]+)/?$ somepage.php?id=$1
Unless you don't intend to use the query string for anything else, you should be using the QSA flag - otherwise it'll drop the rest of your query string when the rule is applied.

Depending on the way your server is set up, you may also need to prepend /? to that expression (after the caret), otherwise it won't catch things where the evaluated URL is something like /home. This isn't always necessary, but adding it can't cause any problems, and will potentially solve a few.

You should also remove the $ from the end of it, unless you only want to capture things like /home and not /home/blue/fish. Depending on how much you care about the blue fish, you may also wish to capture that and do something with it (although you don't necessarily need to do that here, as it's also available from PHP via $_SERVER['REQUEST_URI']).

If you want to learn a bit more about regex, this site (http://www.regular-expressions.info/) is excellent.