Search code examples
apache.htaccessmod-rewriteurl-rewritingwebserver

HTACCESS: Check if a File (.JS File for Example) Is “Requested by a Webpage” OR “Viewed Directly Throuh Its URL”


Please I need help guys.

Is it possible to check if a file is requested by a page or if it is being viewed directly through it's URL?

Let's say we have a JavaScript file named file.js and I have a page named page.html and on the page, we linked to the JS file to use it for some functions.

This what I have tried:

RedirectMatch 301 ^/.*$ https://example.com

With the above code, the file.js redirects to https://example.com when it is viewed through its URL. This is one thing I actually want. But when the file is requested by the page.html, it doesn't show up. It seems to have been redirected as well. I want it to be served when it is requested by the page.

How can I through the HTACCESS check if file.js is requested by page.html to allow its usage but redirect it if it is requested directly with its URL?

ALSO: Maybe this can be done by checking the URL through which the file is being requested from wether it matches the file url or not. I don't know by the way...

I need your help.

Thank you!

Edit:::

I want to know if I can set it up so that even after it is seen through a page, it still cannot be viewed directly through its URL. And if what I'm requesting is possible by the way.


Solution

  • Although it appears different, it's not. A page that includes the js file will effectively "directly access" it in order to load it. Any differences that there are can easily be faked by anyone wanting to grab the file (such as the referrer header used on the link in the comments).

    If the file is available, it's available. It can't be stopped from being accessible while still being accessible. A page loading it works no differently from loading the URL directly.

    What you may want to look in to is obfuscation so that the file is not as usable as it is in the source format. Basically making the JS unreadable for humans although to a point it can still be reversed.

    Another option, if you're wanting to hide delicate or private JS code, and the best if you can use it, is to run the JS on the server if possible. Then folks can only get the results of what it produces rather than the code itself.

    Anyway I'm guessing what your issue is. Perhaps lay out what problem you're trying to solve (in a new question), as suggested in the comments, and then perhaps folks might have other helpful suggestions.