Home > OS >  Redirecting all the traffic to index.php with unlimited parameters
Redirecting all the traffic to index.php with unlimited parameters

Time:09-23

Let me introduce you to my problem. I am newbie to .htaccess... Untill my .htaccess worked pretty well, here is the code I was using for two url parameters (f.e. www.page.com/en/articles):

# DISABLE CACHING

<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
Header set Access-Control-Allow-Origin "*"
</IfModule>

Options -Indexes

RewriteEngine on

RewriteCond %{HTTPS} on
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

RewriteRule ^(.*)$ index.php [R=301,L]

RewriteRule ^([^/]*)(.*)$ index.php?lang=$1&url=$2 [L]

But when I added third parameter like so (f.e. www.page.com/en/articles/20):

...

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

Then echo $_GET['lang'] returned "en" (thats OK) BUT echo $_GET['url'] returned "/articles/20" and $_GET['id'] didnt even exist (Thats NOT OK).

Can anyone please explain to me what in the world am I doing wrong ?

Thanks in advance

CodePudding user response:

Rather than writing increasingly complicated regular expressions in apache configs, just bulk-rewrite everything to simply index.php and do the parsing in the application. You're already using index.php as a request router anyhow.

// eg: /en/articles/20?other_query=vars&might=be_here
$uri = $_SERVER['REQUEST_URI'];

$parts = explode('/', parse_url($uri)['path']);

var_dump($parts);

Output:

array(4) {
  [0]=>
  string(0) ""
  [1]=>
  string(2) "en"
  [2]=>
  string(8) "articles"
  [3]=>
  string(2) "20"
}

You got more/better tools to parse the URI in PHP.

This also has the bonus effect of making your application more easily portable as you don't need to reimplement as much config if you move to another HTTPd like nginx.

CodePudding user response:

You want to capture up to a / so try:

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

But better maybe do the three cases notice no [L]:

RewriteRule ^([^/]*)$ index.php?lang=$1
RewriteRule ^([^/]*)/([^/]*)$ index.php?lang=$1&url=$2
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ index.php?lang=$1&url=$2&id=$3

To exclude a directory such as 'images` use a pass-thru. If they are not in another directory you will have to match the type or extension. Do this before the other rules:

RewriteRule ^images/.*$ - [PT]
  • Related