I want to redirect to another url when request come to apache http for download a file
for example, client call https://example.com/download/apps/v1.01.apk
/download/apps/v1.01.apk is a real path
I want when call url apache prevent to download it and redirect to another url
CodePudding user response:
For this, you will need to use a .htaccess file.
Create a .htaccess file, in the root of your project and type this into the file:
RewriteEngine on
Options -Indexes -Multiviews
RewriteRule ^(v1\.01\.apk)$ your-new-url.php
CodePudding user response:
It's worth keeping in mind that when the web server first receives a request, the URL is just a string, and the server has to decide what to do.
One of the things it can do is look for a file on disk whose name matches the URL. If it finds a file, it can decide what to do with that information, perhaps combined with other information the browser sent in the request, or information it finds about the file.
Eventually, the server will come up with a response - maybe a response with the content of the file it found; maybe the result of running a particular script; maybe a response indicating a redirect to a different URL.
With most web server software, you can configure all of these decisions, in very flexible ways. So you can say "if the URL has a v in it, look for a file in this folder; if it exists, run this PHP script with the file name as an argument; if it doesn't, issue a redirect response to a URL where the v is replaced with an x".
For Apache, you will see a lot of advice to use .htaccess files to do this. These are not the primary configuration for Apache, but they are a convenient place to put extra configuration when you are using a shared server and can't edit the main configuration for security reasons.
The specific configuration line used to trigger a redirect response in Apache looks like this:
RewriteRule pattern-to-match-against-request url-to-redirect-to [R]
The first argument is a "regular expression" which can be as general or specific as you want. Note that .
means "any character", so if you want to match a dot specifically, write \.
The second argument can contain variables like $1 and $2 which refer to parts of the requested URL "captured" by putting them in brackets in the pattern.
The [R]
at the end can also have a type, like [R=temp]
or [R=307]
, which will change how the browser handles the redirect, caches it, and so on. There are also other flags your can add, like [R,NC]
for "Redirect, Not Case-sensitive".
Finally, you can add any number of RewriteCond
lines before a rule, such as RewriteCond -f %{REQUEST_URI}
meaning "if a file exists with the same name as the requested URL.