Chris
Chris

Reputation: 256

Htaccess rewrite for dynamic file name and rewrite path

I'm trying to do a rewrite, where if the page doesnt exist, it rewrites to a category page. Its a bit different to the normal RewriteCond %{REQUEST_FILENAME} -f as the page name is dynamic based on the URL.

If somebody visits a dynamic path name such as "/contacts"

I first want it to check if the following folder/file exists based on the path name:

/[dynamicpath]/[dynamicpath].php

example:

/contacts/contacts.php

If that doesnt exist, rewrite to the following page

/categories/category/category.php?cat_url=[dynamicpath]

example:

/categories/category/category.php?cat_url=contacts

I've tried the below, but it fails with the first RewriteRule triggering when the file exists and goes straight to the category rewrite.

RewriteCond %{SCRIPT_URL} ^(.+)
RewriteCond %{DOCUMENT_ROOT}/%1/%1.php !-f
RewriteRule (.+)/?$      $1/$1.php  [QSA,L]

RewriteRule ^([\w-]+)/?$                /categories/category/category.php?cat_url=$1        [QSA,L]

Upvotes: 0

Views: 684

Answers (2)

Chris
Chris

Reputation: 256

I found the answer by checking the server variables being passed and discovered %{REQUEST_FILENAME} included the full file path (document_root+filename).

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}%{REQUEST_URI}.php -f
RewriteRule ^(.+)/?$ $1/$1.php [L]

RewriteRule ^(.+)/?$ categories/category/category.php?cat_url=%{REQUEST_URI} [QSA,L]

Upvotes: 0

anubhava
anubhava

Reputation: 785651

You may use these rules in your site root .htaccess:

RewriteEngine On

# attempt rewrite to /[dynamicpath]/[dynamicpath].php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1/$1.php -f
RewriteRule ^(.+?)/?$ $1/$1.php [L]

# else rewrite to categories/category/category.php?cat_url=...
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)/?$ categories/category/category.php?cat_url=$1 [QSA,L]

Upvotes: 0

Related Questions