skip to Main Content

I am trying to get a redirect rule working in a subfolder so I can rewrite a URL from:

https://www.somesite.co.uk/api/FormEntries.php?id=1

To (which is how users would access the above to provide a more friendly URL):

https://www.somesite.co.uk/api/FormEntries/1

Where:

  • Name of php file is the first variable so could have /api/OtherObject/1
  • Number on end is the Id of the record

This is the content of the .htaccess file where I only want to affect this sub-folder.
When using online testers they seem to suggest the rule works until I add the RewriteBase value but I have tried adding the main rewrite rule to the top level .htaccess too as the first rule with an [L] tag on the end but I still cannot get it to work. Rewrite works in general on the server so I don’t think it is a hosting issue but not sure if WordPress is causing any other conflict in the parent folder.

These are the contents of the .htaccess file:

RewriteEngine On
RewriteBase /api/
RewriteRule ^api/([a-zA-Z0-9_-]+)/?([0-9]+)?$ /api/$1.php?id=$2 [NC,QSA,L]

Thanks
Robin

2

Answers


  1. Chosen as BEST ANSWER

    I have finally managed to fix it and this combination is working with the `.htaccess' file in the subfolder:

    Options +FollowSymLinks -MultiViews
    DirectoryIndex FormEntries.php
    
    RewriteEngine On
    RewriteBase /api/
    
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ([a-zA-Z0-9_-]+)/?([0-9]+)?$ /api/$1.php?id=$2 [NC,QSA,L]
    

    So now /api/FormEntries/1 goes to /api/FormEntries.php?id=1 successfully showing the output from the API in a more user friendly way.

    I have left in the flags as NC is useful for not being case sensitive so it will still work if all lowercase, QSA is useful to pass on any additional query parameters that are added and L to avoid processing other rules if this one matches so all seems to be doing what I had hoped it would do.


  2. If the .htaccess file is at the root of the api directory, you don’t want to reference it again in your rules or it will try to find a api directory inside api directory, which is not the case and obviously leads to a 404 page.

    So this one line htaccess inside api directory will work as I tested in a WordPress with your file structure in the below comment.

    RewriteRule ^(.*)/(.*)                 $1.php?id=$2 [QSA,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search