Search code examples
apache.htaccessmod-rewrite

.htaccess rewrite returning Error 404


RewriteEngine on
RewriteCond %{QUERY_STRING} (^|&)public_url=([^&]+)($|&)
RewriteRule ^process\.php$ /api/%2/? [L,R=301]

Where domain.tld/app/process.php?public_url=abcd1234 is the actual location of the script.

But I am trying to get .htaccess to make the URL like this: domain.tld/app/api/acbd1234. Essentially hides the process.php script and the get query ?public_url.

However the script above is returning error 404 not found.


Solution

  • I think this is what you are actually looking for:

    RewriteEngine on
    
    RewriteCond %{QUERY_STRING} (?:^|&)public_url=([^&]+)(?:$|&)
    RewriteRule ^/?app/process\.php$ /app/api/%1 [R=301,QSD]
    
    RewriteRule ^/?app/api/([^/]+)/?$ /app/process.php?public_url=$1 [END]
    

    If you receive an internal server error (http status 500) for that then check your http servers error log file. Chances are that you operate a very old version of the apache http server, you may have to replace the [END] flag with the [L] flag which probably will work just fine in this scenario.


    And a general hint: you should always prefer to place such rules inside the http servers (virtual) host configuration instead of using dynamic configuration files (.htaccess style files). Those files are notoriously error prone, hard to debug and they really slow down the server. They are only supported as a last option for situations where you do not have control over the host configuration (read: really cheap hosting service providers) or if you have an application that relies on writing its own rewrite rules (which is an obvious security nightmare).


    UPDATE:

    Based on your many questions in the comments below (we see again how important it is to be precise in the question itself ;-) ) I add this variant implementing a different handling of path components:

    RewriteEngine on
    
    RewriteCond %{QUERY_STRING} (?:^|&)public_url=([^&]+)(?:$|&)
    RewriteRule ^/?app/process\.php$ /api/%1 [R=301,QSD]
    
    RewriteRule ^/?api/([^/]+)/?$ /app/process.php?public_url=$1 [END]