Adnan Afzal
Adnan Afzal

Reputation: 197

RegExp htaccess in php

I want to redirect all my requests to my index.php page and get the url there.

Here is my .htaccess file code.

RewriteEngine On
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

My question is, why should I have to give $1 after url= ?

Thanks.

Upvotes: 1

Views: 56

Answers (3)

Álvaro González
Álvaro González

Reputation: 146660

The original URL can be fetched from $_SERVER['REQUEST_URI'] so, strictly speaking, you don't need mod_rewrite to transmit it explicitly.

For instance, this is the ruleset used by the Lumen framework:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

Whatever, if you prefer to pass it anyway, you don't need to capture it explicitly since the full matched expression is always at $0 automatically:

RewriteRule ^.*$ index.php?url=$0 [QSA,L]

Upvotes: 1

J. A. Streich
J. A. Streich

Reputation: 1712

The $1 matches with whatever is the capture (between the parens), in this case the URL of the page they are trying to go to.

This allows you to see what page they are trying to visit in your php script using $_GET['url'].

Without it, you could still get the requested URL in a couple of different way, but this is the easiest and most likely to be accurate.

Upvotes: 1

Mahmudur Rahman
Mahmudur Rahman

Reputation: 765

When you use the braces (.*), that means you are capturing the group. you can use the content with $1 . if you don't use $1 then you will not get the url here: url=$1 . For details: http://www.regular-expressions.info/brackets.html

Upvotes: 1

Related Questions