user2482153
user2482153

Reputation: 21

Site global htaccess rewrite rule

I have a site (php) with a bunch of files, e.g. directory.php, profile.php etc.

On each page there are actions that mean I have to use get variables such as:

- directory.php?action=seed&ref1=abc&ref2=123
- profile.php?action=list&ref1=abc
- profile.php?action=full

Is it possible to have a rewrite rule in the htaccess, that I can use all of these links such as:

- directory/seed/abc/123
- profile/list/abc
- profile/full

without having to write rules for each individual file?

I have used rules like:

RewriteRule ^profile/(.*)/(.*) /profile.php?action=$1&ref=$2 [QSA,NC,L]

Before, but not sure if there is a way to use this one rule for all files, rather than duplicate the rule for each file.

Thanks

Upvotes: 2

Views: 201

Answers (2)

Jon Lin
Jon Lin

Reputation: 143906

You'll need different rules for the different number of parameters, unless you're fine with having empty values for them:

RewriteEngine On
Options -Multiviews

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ /$1.php?action=$2&ref1=$3&ref2=$4 [L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ /$1.php?action=$2&ref1=$3 [L]

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)/([^/]+)/?$ /$1.php?action=$2 [L]

Or if you don't care about blank parameters, you can just use a single rule:

RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)/([^/]+)(?:/([^/]+)|)(?:/([^/]+)|)/?$ /$1.php?action=$2&ref1=$3&ref2=$4 [L]

Upvotes: 1

Mouhamed Halloul
Mouhamed Halloul

Reputation: 209

i don't think that you can have one rule for all, but why not work with MVC structure and have a controller who manage all your request and actions and a the view will manage your links and rendering ... for more informations take a look at this : http://www.onextrapixel.com/2012/03/14/a-detailed-overview-of-the-model-view-controller-mvc-coding-structure/

Upvotes: 1

Related Questions