Search code examples
regex.htaccess

Rewriting URL from other than root folder with .htaccess


I am trying to make URL rewrite to nice looking URL with .htaccess. I was trying so many ways and always get or error 500 or nothing is happening. My folder tree looks like this:

 root
    index.php
    .htaccess
    p
        .htaccess
        citati.php 
        ...

What I am trying to do is from my "p" directory when someone goes to https://example.com/p/citati/Test-test to rewrite that to https://example.com/p/citati?autor=Test-test so I can have $_GET["autor"] in my citati.php file. I have many .php files in "p" directory so that is also what I need to worry about when rewriting. This is my .htaccess from root

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
RewriteRule ^(.+)p/citati\/(.+)$ p/citati?autor=$1 [NC]

And this is what I have now in my "p" directory .htaccess file:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L,QSA]
RewriteRule ^p/citati\/(.+)$ p/citati?autor=$1 [NC]
</IfModule>

It doesn't matter if I can achieve this from root .htaccess file or from "p" directory .htaccess I just want somehow to do this.


Solution

  • As per your shown samples, please do have your root's htaccess Rule file as follows.

    RewriteEngine ON
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]
    

    For your p directory/folder have that htaccess Rule file as follows. You need to use same rules from root htaccess, you could inherit it.

    RewriteOptions InheritBefore
    RewriteEngine ON
    RewriteBase /p/
    
    RewriteCond %{THE_REQUEST} \s/(citati[^.]*)\.php\s [NC]
    RewriteRule ^ %1? [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^([^/]*)/(.*)/?$ $1.php?autor=$2 [NC,L]