Navneet Saini
Navneet Saini

Reputation: 944

Not getting how rewriting URLs exactly works

I am not able to grab the concept behind rewriting URLs regardless of so many articles on the web about it.

Suppose absolute path of the webpage I want to see is www.abc.com/games.php?game=1. I want the link www.abc.com/games/game/1 to redirect to the above page.

Wouldn't this rule work for it?

RewriteRule games/game/([^/\.]+)/?$ games.php?game=$1 [L]

My .htaccess file

RewriteEngine On
RewriteBase /
RewriteRule games/game/(\d+)/?$ games.php?game=$1 [L, QSA]

Upvotes: 1

Views: 65

Answers (2)

user4035
user4035

Reputation: 23729

"Wouldn't this rule work?"

RewriteRule games/game/([^/\.]+)/?$ games.php?game=$1 [L]

Yes, it would work. But your regular expression can be simplified and improved:

  1. (...) - characters in brackets will be captured - correct, that's what we need.

  2. [^/\.] - will match any characters, that are not in character class; i.e. any symbol, that is not a slash / and not a dot . - this is not fully correct. We need to match any number of digits: \d+. But your regexp will match non-digital symbols as well.

  3. /?$ - possible slash at the end of string

So, we can rewrite your regexp like this:

^games/game/(\d+)/?$

I added a cap symbol at the beginning, so we can be sure, that the URL starts from "games".

This site may be helpful:

http://www.regular-expressions.info/

Upvotes: 2

Kristian Vitozev
Kristian Vitozev

Reputation: 5971

When you are dealing with query strings and rewrite rules, you need the "QueryString Append" option.

qsappend|QSA’ (query string append) This flag forces the rewrite engine to append a query string part of the substitution string to the existing string, instead of replacing it. Use this when you want to add more data to the query string via a rewrite rule.

So, you should use this:

RewriteRule games/game/(\d+)/?$ games.php?game=$1 [L, QSA]

Now you can acccess $_GET['game'] from your processing page.

Upvotes: 0

Related Questions