Home > OS >  Rewriting a url that matches a specific pattern
Rewriting a url that matches a specific pattern

Time:01-10

I have a .htaccess file with the following lines

# ErrorDocument 404 /error/404.php

Options All -Indexes -MultiViews

RewriteEngine On

# Allow urls to not include the .php extension
RewriteCond %{REQUEST_URI}/$1.php -f [NC]
RewriteRule ^(. ?)/?$ $1.php [L]

# Silent Redirect from any url ending with mcc-* to show.php?id=mcc-*
# This is the portion that isn't working
RewriteCond %{REQUEST_URI} (mcc-[\d] )\.php$
RewriteCond %{REQUEST_URI}/$1.php -f [NC]
RewriteRule show.php?id=$1 [L]

I am trying to find any url that ends with the pattern (mcc-[\d] ) and redirect it to show.php?id=%pattern%, however attempting to access a page that matches this pattern simply returns a 404 error as there is no file mcc-*.

CodePudding user response:

With your shown samples please try following .htacess rules file. This code internally rewrites to show.php file. Please make sure to:

  • Keep your .htaccess file along with your show.php file.
  • Make sure to clean your browser cache before testing your URLs.
RewriteEngine ON

# Allow urls to not include the .php extension
RewriteCond %{REQUEST_URI}/$1.php -f [NC]
RewriteRule ^(. ?)/?$ $1.php [L]

## Rules for internal rewrite here.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(mcc-.*)/?$ show.php?id=$1 [QSA,NC,L]
  • Related