Ron Ron - 3 years ago 212
PHP Question

Are if statements possible in htaccess

This code works fine:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^([a-zA-Z0-9-]+)/?$ index.php?seo_name=$1

But, I want to add if statements like this, is that possible and how?

if seo_name = cccc, go to page cccc.php

if seo_name = dddd, go to page dddd.php

and so forth and so on.

Thank you.


Answer Source

You can use RewriteRule and take advantage of the regexes directly. I think they are enough to discriminate your pages.

RewriteRule ^(.*?)$ $1.php

Or if you just need specific pages to be replaced you can do like this:

RewriteRule ^mypage$ mypage.php

Note that you can even use these to pass query strings to php to discriminate directly in the source code, then a php if with include()s may do the trick:

RewriteRule ^page([0-9]+)$ page.php?id=$1

Note that these URL replacements aren’t redirections and they’re not “seen” by the browser, so any relative file required by the html will be taken from the path of the virtual folder.

EDIT: my suggestion for you is to make htaccess to point to a php file (let's call it hub.php):

RewriteRule ^cccc$ hub.php?id=cccc
RewriteRule ^dddd$ hub.php?id=dddd

Now php will do the trick, in hub.php:

if ($_GET['id'] == 'cccc') {

if ($_GET['id'] == 'dddd') {

I think there are faaaaar better ways to do this, but if you prefer this way... And this will make it work without changing the code in cccc.php and dddd.php

Just pass the "great" jobs to php, don't make big .htaccess files (.htaccess modifications require Apache to reload, php files do not).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download