apache.htaccessmod-rewrite

Rewrite rule to resolve 2 use cases


I have a rewrite rule in my .htaccess file:

RewriteRule ^projects/?([a-zA-Z0-9-]+)?/?([a-zA-Z0-9-]+)?$ /projects/$1/seo.$2.php  

For example, the following rule works fine and I would like to keep it as is:

URL: domain.com/projects/book/read-more opens /projects/book/seo.read-more.php page

What I need is, in addition, to modify it or add another rule to display only the directory and resolve in the index.php file if the address ends with the directory.

URL: domain.com/projects/book to open /projects/book/index.php page

I've tried putting the following rule above the current one but it didn't work.

RewriteRule ^projects/?([a-zA-Z0-9-]+)?$ /projects/$1/index.php [NC,L]

What am I missing?


Solution

  • Could you try these:

    # Match the directory and point to index.php
    RewriteRule ^projects/([a-zA-Z0-9-]+)/?$ /projects/$1/index.php [NC,L]
    
    # Match to handle additional segments
    RewriteRule ^projects/([a-zA-Z0-9-]+)/([a-zA-Z0-9-]+)/?$ /projects/$1/seo.$2.php [NC,L]
    

    I tested them on htaccess.madewithlove.com and got the results you were expecting