Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters in Rewrite Rules with specifying the .php file name?

I have a site, which successfully passes the content after the first slash to a specified .php file. (elegantly: remove ".php")

site.com/azamat to site.com/azamat.php

RewriteCond %{REQUEST_FILENAME} !-d    
RewriteCond %{REQUEST_FILENAME}\.php -f   
RewriteRule ^(.*)$ $1.php [NC]

How can I add additional parameters to these rules, so I can pass "page" parameters, like:

site.com/azamat/bagatov to site.com/azamat.php?page=bagatov

or

site.com/thisisthefile/andparams to site.com/thisisthefile.php?page=andparams

like image 747
Gábor DANI Avatar asked Nov 04 '22 18:11

Gábor DANI


1 Answers

Try adding these rules (keep the ones you already have):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} ^/([^/]+)/.+$
RewriteCond %{DOCUMENT_ROOT}/%1.php -f
RewriteRule ^([^/]+)/(.+)$ /$1.php?page=$2 [L]

This is more or less like what you've got with the exception of using a %1 backreference to check if the first part of the URI exists as a php file. This is the match for the first part:

RewriteCond %{REQUEST_URI} ^/([^/]+)/.+$

And this is the fheck to see if the ([^/]+) grouping exists as a php file:

RewriteCond %{DOCUMENT_ROOT}/%1.php -f

Everything else is to match what's after the first / and make that the page query string param.

like image 67
Jon Lin Avatar answered Nov 08 '22 14:11

Jon Lin