Search code examples
apache.htaccessmod-rewriteurl-rewritingfriendly-url

Why can't I access my page and query params after htaccess rules rewrite the url?


  1. I have a url of the form --> https://websitename.com/content?id=xyz
  2. I want to rewrite the url in the form --> https://websitename.com/content/xyz
  3. I want to be able to access the query param (id) and its value (xyz) on the content page after the url has been rewritten
  4. All pages are *.php pages
  5. I've used the following htaccess rewrite rule
    RewriteEngine On
    
    # Hide .php file extension in the urls
    RewriteRule ^([^/.]+)$ $1.php
    
    RewriteRule ^content/([A-Za-z0-9-]+)/?$ content?id=$1 [NC,L]
    
    
  6. When I navigate to the rewritten url, it doesn't work and I get the following error: "Not Found The requested URL was not found on this server"
  7. I also can't access the query parameter and its value on the rewritten url
  8. But, when I enter the original url, that works and I can access the query parameter and its value

I'd appreciate it a ton if someone can help me find out what I am doing wrong and how I can fix this.

Thanks, Dexxterr.


Solution

  • With your shown samples, please try following once. Please clear browser cache before testing your URLs.

    RewriteEngine On
    
    # Hide .php file extension in the urls
    RewriteRule ^([^/.]+)$ $1.php [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^content/([A-Za-z0-9-]+)/?$ content.php?id=$1 [NC,L] 
    

    You may need to use base tag to fix your js and other relative resources. If you are linking js files using a relative path then the file will obviously get a 404 because its looking for URL path. for example if the URL path is /file/ instead of file.html then your relative resources are loading from /file/ which is not a directory but rewritten html file. To fix this make your links absolute or use base tag. In the header of your webpage add this <base href="/"> so that your relative links can load from the correct location.