Search code examples
apache.htaccessmod-rewritexamppfriendly-url

Rewrite rule to redirect two friendly urls to same file


I'm trying to redirect two different url to the same file.

The url are: http://localhost/CLIENTI/HOTEL/cp/amministratori and http://localhost/CLIENTI/HOTEL/cp/amministratori/test

Actually i currently see the first url, but when I open the second one i see a lot of error of files inclusion on client side (es js and css files on header/footer).

This is my .htaccess file:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^dashboard$ dashboard.php [NC,QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^amministratori$ dashboard.php [NC,QSA,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^amministratori/test$ dashboard.php [NC,QSA,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

that was all my htaccess code. The errors are 404 of bootstrap.js and main.js which contains custom code for the frontend. I've understood the problem but I've haven't undersood if there is a solution alternative to the leading slash, because my header and footer are included in php, so in /cp/amministratori they work as now, but obviously if I change with a leading slash they will not work anymore


Solution

  • With your shown attempts, please try following htaccess Rules. Make sure to place your htaccess file along with CLIENTI folder(not inside it).

    Please make sure to clear your browser cache before testing your URLs.

    RewriteEngine On
    
    RewriteBase /CLIENTI/HOTEL/cp/amministratori/
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^dashboard/?$ dashboard.php [NC,QSA,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^/?$ dashboard.php [NC,QSA,L]
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^test/?$ dashboard.php [NC,QSA,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.php [QSA,L]
    

    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.