Apache rewrite rule - prevent rewritten URL appear

2019-08-04 02:56发布

问题:

I have a rewrite rule which is looking for a particular URI. When it matches the particular URL it rewrites it with a proper file path so the required content can be found. It then changes the protocol to HTTPS and allows the request to pass through.

I have two problems;

  1. I don't want the rewritten path to appear in the users browser - i want to maintain the vanity url
  2. I do want the HTTPS protocol to appear indicating to the user that they are accessing the site over a secured conection.

I have tried a couple of options but no success. If i include the [R] flag the URL and protocol remain unchanged but that is not the desired effect

Any suggestions on how i can achieve this?

This is my rule;

RewriteMap redirectsIfSecure txt:/myserver/content/secure_urls.txt
RewriteCond ${lowercase:%{REQUEST_URI}} ^/(.+)$
RewriteCond ${redirectsIfSecure:%1|NOT_FOUND} !NOT_FOUND
RewriteRule ^(.*)$ https://myserver.com${redirectsIfSecure:%1} [PT]

回答1:

From the mod_rewrite documentation:

If an absolute URL is specified, mod_rewrite checks to see whether the hostname matches the current host. If it does, the scheme and hostname are stripped out and the resulting path is treated as a URL-path. Otherwise, an external redirect is performed for the given URL. To force an external redirect back to the current host, see the [R] flag below.

If you rewrite the request to a fully qualified URL (that is, anything starting with http://, https://, etc) that doesn't match your ServerName, then mod_rewrite will issue an HTTP redirect, which will cause the client browser to request the resource from the new location.

If you're not trying to switch between http and https you can use a proxy rule (the P flag) to have Apache make the request on behalf of the client and return the result, thus masking the rewritten URL.

However, if you're trying to upgrade from http to https (or the other way around), this will always require a client redirect.