0

This is my folder structure:

---- downloads
    ---- .htaccess
    ---- index.php
    ---- download 1
    ---- download 2
    ---- download n

.htaccess contents:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^.*index\.php$ [NC]
RewriteCond $1 !^index.php$ [NC]
RewriteRule (.*) index.php?uid=$1 [L]

index.php contents:

<?php
// do stuff

header('Location: http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
?>

I'm redirecting every request for a download, e.g. downloads/download 1 to index.php where I do something and then redirect to the original file, downloads/download 1.

This works out fine except that I don't know how to NOT apply the rewrite rule in .htaccess when the HTTP referrer is index.php.
I tried with RewriteCond %{HTTP_REFERER} !^.*index\.php$ [NC] but it keeps looping.

1 Answer 1

1

In case the HTTP referrer does not end with index.php

!^.*index\.php$

you do the redirect. In your question however you've said, that the referrers ends with downloads/download 1.

The HTTP_REFERER is set by your browser. And your browser will not update the URL.

Next to that, even if your browser would have done, the URL would still not end with index.php but with index.php?uid=downloads%2Fdownload%201.

So you have to re-think how you would like to check for the referrer and how you update the referrer as well. Maybe using a redirect helps with that:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^.*index\.php.*$ [NC]
RewriteCond $1 !^index.php$ [NC]
RewriteRule (.*) index.php?uid=$1 [R,L]
Sign up to request clarification or add additional context in comments.

2 Comments

The browser still gives a "The page isn't redirecting properly" page. What about sending an URL with a GET variable back via PHP, like /downloads/download 1?referred=1. Would that work and how would I check for that one instead of the HTTP referer in the htaccess file?
Ensure that you're not using a firewall/browser, that removes all HTTP_REFERER header for privacy settings. The added query parameter would be easier to check, you can do this with RewriteCond or RewriteRule.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.