0

I would like to redirect all of the following urls if a WordPress user is not logged in (or WordPress cookie is set) using .htaccess.

  1. https://example.com/wp-content/uploads/sample_pdf

  2. https://example.com/wp-content/uploads/sample_pdf/index.html

  3. https://example.com/wp-content/uploads/sample_pdf/index.html#page=1

  4. https://example.com/wp-content/uploads/sample_pdf/index.html#page=2 etc etc

This is what I have tried :

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_COOKIE} !.*wordpress_logged_in.*$ [NC]
    RewriteCond %{REQUEST_URI} ^(.*?/?)wp-content/uploads/sample_pdf/(.+) [NC]
    RewriteRule . http://%{HTTP_HOST}%1/wp-login.php?redirect_to=%{REQUEST_URI} [L,QSA]
</IfModule>

and

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_COOKIE} !.*wordpress_logged_in.*$ [NC]
    RewriteCond %{REQUEST_URI} ^(.*?/?)wp-content/uploads/sample_pdf/.* [NC]
    RewriteRule . http://%{HTTP_HOST}%1/wp-login.php?redirect_to=%{REQUEST_URI} [L,QSA]
</IfModule>

Both of these options redirect the first URL :

  • https://example.com/wp-content/uploads/sample_pdf

But not the others.

Can you please let me know where my regex is going wrong & why it's not grabbing everything in the /sample_pdf directory.

  • "Both of these options redirect the first URL" - Although it shouldn't directly, as the regex in the 2nd condition does not match (in both rule blocks). Is sample_pdf a physical directory on the filesystem? In which case, mod_dir would first issue a 301 redirect to append the trailing slash - then (on the redirected/2nd request) it would match. But this also depends on where exactly you've put these directives in relation to other directives in your .htaccess file - order matters. Please update your question with the contents of your .htaccess file. – MrWhite Apr 24 at 16:50
  • Also, why are you capturing the URL-path before wp-content/? And why are you appending this to the hostname (or start of the URL-path)? From the example URLs given this would result in an erroneous double slash at the start of the URL-path. (?) – MrWhite Apr 24 at 16:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.