Home > Back-end >  .htaccess - Rewrite with multiple parameters not working
.htaccess - Rewrite with multiple parameters not working

Time:10-19

I am creating a rule to display addresses of type :

main.php?cat=MyCategory
main.php?cat=MyCategory&sub=MySubcategory
main.php?cat=MyCategory&sub=MySubcategory&prod=MyProduct

As

MyDomain.com/MyCategory
MyDomain.com/MyCategory/MySubcategory
MyDomain.com/MyCategory/MySubcategory/MyProduct

but there are two problems:

The first problem is that the other links on the displayed page start in the wrong position.

MyDomain.com/MyCategory/MySubcategory/MyProduct/newlink.html

should be referenced to the root, like this

MyDomain.com/newlink.html

Second problem is that from 2nd/3rd URL levels, my references such as javascript, img src and css links are wrong. It looks for these files relative from the up levels url. How do I fix this?

My .htaccess file

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/] )$ principal.php?cat=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/] )/([^/] )$ principal.php?cat=$1&sub=$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/] )/([^/] )/([^/] )$ principal.php?cat=$1&sub=$2&prod=$3  [L]

Tried with:

RewriteCond %{REQUEST_URI} !^/newlink\.html$ 

But not working, any ideas?

CodePudding user response:

For your first query to deal with 4th level .html format URLs try following .htaccess rules file. Make sure to clear your browser cache before testing your URLs.

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*/[^/]*/[^/]*/)([^.]*\.html)/?$  $1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/] )$ principal.php?cat=$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/] )/([^/] )$ principal.php?cat=$1&sub=$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/] )/([^/] )/([^/] )$ principal.php?cat=$1&sub=$2&prod=$3  [L]

For JS/CS rewrite/redirect: You may need to use base tag to fix your js and other relative resources. If you are linking js files using a relative path then the file will obviously get a 404 because its looking for URL path. for example if the URL path is /file/ instead of file.html then your relative resources are loading from /file/ which is not a directory but rewritten html file. To fix this make your links absolute or use base tag. In the header of your webpage add this <base href="/"> so that your relative links can load from the correct location.

  • Related