palAlaa
palAlaa

Reputation: 9858

Redirect to another directory if url match pattern htaccess

I have WordPress installation with a subdirectory has the same name as the page. I rename this directory and I want to redirect to it whenever a specific URL has been requested.

In my wordperss I have >>> /resources path and I have /resources/page1 /resources/page2 etc

I also have a subdirectory called resources and have subdirectories called page1 and has a file1.zip file.

I need whenever the user asks for /resource/page1 to open it from WordPress and whenever the user asks for /resource/page1/file1.zip to download it from the directory. This subdirectory can have multi subdirectories, eg. /resources/page1/releases/v1/file1.zip

I am fine with renaming the subdirectory as long as I can handle the redirection.

I tried these rewriting conditions but unfortunately, I don't understand them properly. In the .htaccess of the main WordPress I added

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteRule ^resources/([^/]+/.+)$ /resources1/$1 [R,L]
</IfModule>



but this rewriting it's not working

Upvotes: 0

Views: 752

Answers (1)

04FS
04FS

Reputation: 5820

The WP default routing will rewrite all requests that do not match a physically existing file or folder, ot its own index.php - so you need to do your additional rewrite before this WP stuff.

And you can not match just resources/(.+) here - because you have /resources/page1 as an existing WordPress page, and that one you don’t want to rewrite.

So demand at least one additional “folder” after resources/ first.

RewriteRule ^resources/([^/]+/.+)$ /resources1/$1 [R,L]

[^/]+ means, one or more characters out of the negated characters class [^/] first - that matches any character but a /.

By demanding an additional / after that, we have made sure, that we match at least one additional folder below resources/.

And then .+ matches one or more arbitrary characters again, including slashes, so that you can have foo.zip or bar/foo.zip or even bar/baz/foo.zip after that.

Upvotes: 1

Related Questions