Home > Software engineering >  htaccess subfolders silent redirect based on how many subfolders the url/link has
htaccess subfolders silent redirect based on how many subfolders the url/link has

Time:10-13

I have the fallowing situation

Main website https://www.example.com

I want:

  1. every https://www.example.com/folder1/folder2/folder3/ to silent redirect to https://www.example.com/folder1/index.php?d2=folder2&d3=folder3
  2. every https://www.example.com/folder1/folder2/folder3/folder4/ to silent redirect to https://www.example.com/folder1/secondindex.php?d2=folder2&d3=folder3&d4=folder4

I created a .htaccess file in https://www.example.com/folder1/

This is the content

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^([^/] )/(.*)$ index.php?d2=$1&d3=$2 [L,QSA]
RewriteRule ^([^/] )/([^/] )/(.*)$ secondindex.php?d2=$1&id3=$2&id4=$3  [L,QSA]
</IfModule>

The problem is that for this type of links https://www.example.com/folder1/folder2/folder3/ it redirects ok to https://www.example.com/folder1/index.php?d2=folder2&d3=folder3, but for the second type of links it does not work.

How can I fix it?

CodePudding user response:

With your shown samples please try following .htaccess rules file. based on your shown samples and attempts.

Make sure to:

  • Place your .htacess file inside folder1 folder.
  • index.pp and secondindex.php files also present inside folder1.
  • Clear your browser cache before testing your URLs.
RewriteEngine ON
RewriteBase /folder1/

##Internal rewrite for URL: https://www.example.com/folder1/folder2/folder3/folder4
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/([^/]*)/([^/]*)/([^/]*)/?$ secondindex.php?d2=$1&d3=$2&d4=$3 [QSA,L]

##Internal rewrite rule for URL: https://www.example.com/folder1/folder2/folder3/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(?:[^/]*)/([^/]*)/([^/]*)/?$ index.php?d2=$1&d3=$2 [QSA,L]
  • Related