1

I am new to using htaccess and mod_rewrite, so I have just about managed to get mine functioning to rewrite my GET page variable to examples.com/page_name/

However, this requires a / after it, I know it is explicitly added into the rewrite, but if I remove it, then I get a 500 error and I've tried adding a ? after it, which would make it optional according to resources I found online, however, it again gives me a 500 error, is there any better way of writing this too?

RewriteEngine On RewriteRule ^([^/]*)\/$ /?page=$1 [L] 
1
  • RewriteRule ^([^/]*)(?:\/)?$ /?page=$1 [L] is what you want. Commented Jan 13, 2015 at 12:17

2 Answers 2

3

You get a 500 error because you have created an infinite loop.

Explanation: (when trailing slash is made optional)

  • domain.com/page_name/ is rewritten to /?page=page_name
  • /?page=page_name means /index.php?page=page_name
  • but now your rule matches index.php too
  • --> LOOP

To avoid it, you can use this code instead

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^/]+)/?$ /?page=$1 [L] 

This code checks if request URI is not an existing file/folder before rewritting.
Your rule could do the trick only if you don't make trailing slash optional.

RewriteRule ^([^/]+)/$ /?page=$1 [L] 

And it would be a better idea since you won't have duplicate content (2 different urls -with/without trailing slash- giving same content: bad for search engines).

Conclusion: choose one format but not both. If you choose without trailing slash format then you can use my first part of code (you can remove ?). Otherwise, you can choose my second (the one looking almost the same as yours).

Note: you don't need to escape / with mod_rewrite

Sign up to request clarification or add additional context in comments.

Comments

0

The slashes are escaped, so if you want to remove the trailing one, you have to remove the anti-slash too.

RewriteEngine On RewriteRule ^([^\/]*)$ /?page=$1 [L] 

If you want to make the trailing slash optional, try this:

RewriteEngine On RewriteRule ^([^\/]*)\/?$ /?page=$1 [L] 

1 Comment

Unfortunately, this won't solve anything at all. You can see my answer about it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.