Home  >  Q&A  >  body text

Use .htaccess to rewrite file paths to file names via query strings

I'm having trouble rewriting file paths using query strings

I'm trying to get a URL like this:

https://url.com/products/1_Samsung_Galaxy

and rewrite the request to my server like this:

https:url.com/model.php?id=1&title=Samsung_Galaxy

This is what my htaccess looks like so far:

RewriteEngine On

#rewrite no ending files to .php if file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !products/
RewriteRule ^([^.]+)$ .php [NC,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/products/([1-9]+)(.*)$ model.php?id=&title= [NC,L]

With the current configuration, requests are sent to a file named products.php that is in the same directory as model.php, but appears to be in a different directory because some script files are referenced in products.php with relative paths Will throw exceptions if the object they contain does not exist.

Actually, my main problem is that I don't know apache syntax or how it works, and I'm having a hard time finding resources where I can learn about apache. For some reason the apache documentation isn't much help. If there's a good resource for learning how to write apache files, I'd love to check it out as well.

P粉035600555P粉035600555315 days ago539

reply all(1)I'll reply

  • P粉463824410

    P粉4638244102024-01-02 10:59:01

    Your question is a bit vague, but I think this is what you are looking for:

    RewriteEngine On
    
    # rewrite /products/ to /model.php/.....
    RewriteRule ^/?products/(\d+)(.*)$ /model.php?id=&title= [L]
    
    # rewrite to "...php" if such file exists
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ^ %{REQUEST_URI}.php [L]

    These rules will work if implemented in the http server's host configuration. Alternatively, if you do not have access to the file, you can access it in the distributed configuration file (".htaccess") located in the DOCUMENT_ROOT folder of the http host.

    Main differences from your attempt:

    • The destination path is written as an absolute path. This solves the problem of requests being rewritten to different folders.
    • Implement the exception rewrite to /model.php first, so it is executed higher in the file because rules are processed from top to bottom. This saves some conditions.

    You also mentioned that you are "unfamiliar with apache syntax" and would have trouble finding resources to learn it.

    I always recommend the official documentation for the apache module. They are of excellent quality and provide great examples:

    https://httpd.apache.org/docs/current/mod /mod_rewrite.html

    reply
    0
  • Cancelreply