Per
Per

Reputation:

Help with regular expression with mod_rewrite

I have links like these that I want to change:

mypage.com?page=missions&id=5
mypage.com?page=hello

I tried to change them into easier links with this:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)$ /index.php?page=$1&id=$2 [L]

It works but if I want to access pages like (mypage.com?page=hello) I have to write:

mypage.com/hello/

and if I write without the slash in the end like this

mypage.com/hello

it doesn't work.

How do I fix it? :)

Upvotes: 1

Views: 272

Answers (3)

Per
Per

Reputation:

I read about the trailing slash with SEO (didn't know about it, thank you mathew!) and the final result was this:

RewriteRule ^([a-zA-Z0-9_-]+)/$ /index.php?page=$1 [L]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/$ /index.php?page=$1&id=$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ http://www.mypage.com/$1/ [R=301,L]

So now I force it to have a trailing slash.

Upvotes: 0

molf
molf

Reputation: 75035

This should work:

RewriteRule ^([^/]*)(/([^/]*))?$ /index.php?page=$1&id=$3 [L]

This will make the slash optional by including it in an optional group (denoted by (...)?), along with the optional second half of the query string. Since this introduces a new group between the first and second (left parenthesis determines the order), we have to change the second backreference from $2 to $3.

If the logic becomes much more complex than this, it may be easier to split up the rules.

Upvotes: 3

Matthew
Matthew

Reputation: 1875

You could add a second rule that omits the second parameter and optionally the slash:

RewriteRule ^([^/]+)/?$ /index.php?page=$1
RewriteRule ^([^/]+)/(\d+)/?$ /index.php?page=$1&id=$2

This might work too:

RewriteRule ^([^/]+)(?:/(\d+))?/?$ /index.php?page=$1&id=$2

For SEO, you'll probably want to redirect requests missing the slash to the same address with a slash. Use RedirectMatch for that.

Upvotes: 1

Related Questions