skip to Main Content

in Apache htaccess, is there a way to use parameters as sub folders, Without redirecting to the real URL?

for example:

https://example.com/folder1/folder2/a.jpg?version=small

to

https://example.com/folder1/folder2/small/a.jpg

I have tried various things for this but it didn’t work.
for example:

RewriteCond %{QUERY_STRING} ^version=([^&]+)
RewriteRule ^([^/]+)/([^/]+).jpg$ $1/%1/$2 [L]

note:

I also trying to make the versions folder unavailable in direct request

RedirectMatch 403 ^/small/?$

3

Answers


  1. This should point you into the right direction:

    RewriteEngine on
    RewriteCond %{QUERY_STRING} ^version=(w+)$
    RewriteRule ^/?folder1/folder2/(.+)$ /folder1/folder2/%1/$1 [L]
    

    The RewriteCond extracts the word specified as "version" parameter, the RewriteRule internally rewrites the request using the extracted version word and file name.

    Very likely you will have to tweak the details in the implementation to match your specific situation.

    Login or Signup to reply.
  2. you may need to adjust the regular expression in the RewriteRule accordingly. Additionally, make sure to backup your .htaccess file before making any changes to avoid potential issues with your website.

    RewriteEngine On
    RewriteBase /
    # Extract the version parameter from the query string
    RewriteCond %{QUERY_STRING} ^version=([^&]+)
    
    # Rewrite the URL with the version parameter as a subfolder
    RewriteRule ^([^/]+)/([^/]+).jpg$ $1/%1/$2.jpg L
    

    The %1 in the RewriteRule refers to the captured value from the RewriteCond directive, which is the version parameter from the query string.

    Login or Signup to reply.
  3. Yes, you can use dynamic file extensions in the .htaccess file to achieve the desired URL rewriting. To do this, you need to modify the regular expression in the RewriteRule to capture the dynamic extension and use it in the rewritten URL.

    Here’s how you can achieve this:

    RewriteEngine On 
    RewriteBase /
    
    # Extract the version parameter from the query string 
    RewriteCond %{QUERY_STRING} version=([^&]+)
    
    # Extract the file extension from the original request 
    RewriteRule ^([^/]+)/([^/]+).(.+)$ $1/%1/$2.%3 L
    

    The (.+) in the RewriteRule captures the dynamic file extension, and %3 in the substitution represents that captured extension in the rewritten URL.

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