skip to Main Content

I have trouble rewriting virtual directories as variables.. can someone help please?

The URL is:
https://www.example.com/content/index.php?var=1-dKein4i59xcNjfks

I want it to look like:
https://www.example.com/content/featured/1-dKein4i59xcNjfks

where "content" is a real directory and "featured" and "1-dKein4i59xcNjfks" are virtual
my current .htaccess code is incorrect as:

   RewriteEngine On

   RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} content/index.php?var=([^& ]+)
   RewriteRule ^content/?index.php$ /var/%1? [L,R=301]

Can someone assist please? thanks

2

Answers


  1. With your shown samples please try following. Make sure to clean your browser cache before testing.

    RewriteEngine ON
    
    ##Using THE_REQUEST for catching references and using them later on.
    RewriteCond %{THE_REQUEST} s/(content)/index.php?var=(.*?)s [NC]
    RewriteRule ^ /%1/featured/%2? [R=301,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(content)/featured/(.*?)/?$ $1/index.php?var=$2 [QSA,NC,L]
    
    Login or Signup to reply.
  2. rewrite your URL so it looks cleaner, you want to change index.php?var=... to featured/... in the URL, while still letting index.php process the request. Here’s an updated .htaccess code for that:

    RewriteEngine On
    
    # Redirect URL to the cleaner "featured" format
    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9} /content/index.php?var=([^& ]+)
    RewriteRule ^content/index.php$ /content/featured/%1? [L,R=301]
    
    # Internally rewrite the cleaner URL back to index.php with the "var" parameter
    RewriteRule ^content/featured/([^& ]+)$ /content/index.php?var=$1 [L]
    

    How works:
    First RewriteCond and RewriteRule: Captures the var value from index.php?var=... and redirects it to /content/featured/... to give a cleaner URL.
    Second RewriteRule: When someone visits /content/featured/..., it internally rewrites the URL back to index.php?var=..., so index.php can handle it as if the original query was still there.
    Now, visiting https://www.example.com/content/index.php?var=1-dKein4i59xcNjfks will look like https://www.example.com/content/featured/1-dKein4i59xcNjfks without breaking functionality.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search