'how do I rewrite a URL and maintain the file name

I have a rewrite written in my .htaccess file. I am trying to redirect the following

https://olddomain.com/folder/file.pdf to https://newdomain.com/folder/file.pdf. file.pdf can change so I need to change the domain but leave the folder and file name needs to stay what ever it is. it could be file.pdf or file1.pdf etc

I have this code in my .htaccess file

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/folder/(.*)$
RewriteRule ^(.*) https://newdomain.com/folder/%1 [R=301,NC]

If the file.pdf exists on the old server then the redirect works but if the file does not exist on the old server the redirect does not work.

Any help fixing this would be appreciated.



Solution 1:[1]

If the file.pdf exists on the old server then the redirect works but if the file does not exist on the old server the redirect does not work.

That sounds like you've put the rule/redirect in the wrong place. If you have other directives before this redirect that implement a front-controller pattern then you will experience this same behaviour since any request for a non-existent file would be routed to the front-controller (and request for an existing file is ignored) before your redirect is triggered - so no redirect occurs.

If this is the case then you need to move your rule to the top of the file, before any existing rewrites.

RewriteCond %{REQUEST_URI} ^/folder/(.*)$
RewriteRule ^(.*) https://newdomain.com/folder/%1 [R=301,NC]

However, your existing rule is not quite correct. Importantly, you are missing the L flag on the RewriteRule directive and the preceding RewriteCond directive is not required. For example, try the following instead:

RewriteRule ^folder/.* https://newdomain.com/$0 [NC,R=301,L]

This does assume your .htaccess file is located in the document root of the site.

Alternatively, you create an additional .htaccess file inside the /folder with the following:

RewriteEngine On
RewriteRule ^ https://newdomain.com%{REQUEST_URI} [R=301,L]

The REQUEST_URI server variable contains the full URL-path of the request (including the slash prefix).

By default, the mod_rewrite directives in the /folder/.htaccess file will completely override any directives in the parent (root) .htaccess file (the mod_rewrite directives in the parent are not even processed).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1