iosfreak
iosfreak

Reputation: 5238

Mod_Rewrite help!

I have been using mod_rewrite for a while and love it. However, I am kinda stumped on what to do. Here's what I want to do:

I have a mobile version of the website and I was going to redirect http://myflashpics.com/user/flashpics to http://myflashpics.com/mobile/user/flashpics

Here's my code:

RewriteRule user/(.*)/$ /viewer/index.php?profile=$1
RewriteRule user/(.*)$ viewer/index.php?profile=$1

RewriteRule mobile/user/(.*)/$ /mobile/index.php?user=$1
RewriteRule mobile/user/(.*)$ mobile/index.php?user=$1

But when going to the mobile version, it's showing the desktop version? What's up with that?

Thanks, Coulton

Upvotes: 2

Views: 78

Answers (3)

anubhava
anubhava

Reputation: 784908

It is not very clear to me what you're trying to do but you can compress your .htaccess code like this:

Options +FollowSymlinks -MultiViews
RewriteEngine On

RewriteRule ^user/(.*)/?$ /viewer/index.php?profile=$1 [L,NC,QSA]

RewriteRule ^mobile/user/(.*)/?$ /mobile/index.php?user=$1 [L,NC,QSA]

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270599

Your first rule matches ahead of the mobile rules because it's not limited to user/ occurring at the beginning of the string. Prefix it with ^ to indicate the start of the string:

RewriteRule ^user/(.*)/$ /viewer/index.php?profile=$1
RewriteRule ^user/(.*)$ viewer/index.php?profile=$1

RewriteRule ^mobile/user/(.*)/$ /mobile/index.php?user=$1
RewriteRule ^mobile/user/(.*)$ mobile/index.php?user=$1

Upvotes: 0

Tim Stone
Tim Stone

Reputation: 19169

Your regular expression for the first two RewriteRules matches your mobile path as well, since user/(.*)/$ just tests to see if the pattern matches at the end of the request path. You should add ^ to the beginning of your tests so they check that the entire request path matches, as follows:

RewriteRule ^user/(.*)/$ /viewer/index.php?profile=$1
RewriteRule ^user/(.*)$ viewer/index.php?profile=$1

RewriteRule ^mobile/user/(.*)/$ /mobile/index.php?user=$1
RewriteRule ^mobile/user/(.*)$ mobile/index.php?user=$1

As a side note, you could also save the rewrite engine a bit of trouble and reduce your rule set to two rules. I'd also update your capture expressions, since you probably don't watch them to include forward slashes at all:

RewriteRule ^user/([^/]*)/?$ /viewer/index.php?profile=$1

RewriteRule ^mobile/user/([^/]*)/?$ /mobile/index.php?user=$1

Upvotes: 2

Related Questions