skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. You may try these rules in your site root .htaccess:

    # make index.php default handler of a directory
    DirectoryIndex index.php
    
    RewriteEngine On
    
    # add a trailing slash to directories first
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]
    
    # forward to corresponding seo file only if it is present
    RewriteCond %{DOCUMENT_ROOT}/$1/seo.$2.php -f
    RewriteRule ^(projects/[w-]+)/([w-]+)/?$ $1/seo.$2.php [NC,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search