Question mark and query strings in Apache Rewrite Rules


Difficulty

The apache rewrite module is very useful for defining precise URLs according to our needs, hiding also what we don’t want to expose to the final user.

The RewriteCond means “execute the next RewriteRule only if this is true”.
An example can be a redirect in the case of image files not found:

RewriteCond %{REQUEST_FILENAME}! -F
RewriteRule ^(.*).(jpg|png|gif|ico) https://obyte.it/img/404.png [L,R=301]

The RewriteRule means that, if the request is done that matches a first argument (for instance ^(.*)$ Matches any URL except the root server), it will be rewritten as a second argument.

RewriteRule ^api/([_a-zA-Z0-9]{3,30})? api.php?service=$1 [QSA,L]

For example, we might want to rewrite without affecting the input query string.
In this case we can use one of the flags made available
The QSA flag means that if there is a query string passed with the original URL, it will be appended to the rewrite.
For example:

If we re-call that url in this way, queuing a query string:

api/users?id=42

The url would be transformed into:

api.php?service=users&id=42

That’s all for today.
Try it at home!

0
Be the first one to like this.
Please wait...

Leave a Reply

Thanks for choosing to leave a comment.
Please keep in mind that all comments are moderated according to our comment policy, and your email address will NOT be published.
Please do NOT use keywords in the name field. Let's have a personal and meaningful conversation.