简体   繁体   中英

Best practice for a .htaccess internal path rewrite?

We have spend a considerable amount of time looking for a solution else where. We have read and tried the recommended threads. We most likely have a core misunderstanding as to why this, or something along these lines, does not work.

We get a request for a domain:

subdomain.domain.com/embed/34acb453bc4a53abc

We want to leave the URL as it is, but need to direct this to an internal vhost:

embed.example.com/34acb453bc4a53abc

Once the request is directed to this, our system can interpret the 34acb453bc4a53abc and return the appropriate data.

We tried the following (and variations of it) we just get nothing to work.

RewriteCond ^embed\/(.*)$ [NC]

RewriteRule ^ https://embed.example.com%{REQUEST_URI} [L,NE,P]

internal path rewrite

Just to clarify, you can't internally rewrite the request across different hosts. You need to configure a reverse proxy using mod_proxy and related modules. This is what the P flag on the RewriteRule directive is doing... it's passing the request to mod_proxy (providing this is already correctly configured in the server config).

 RewriteCond ^embed\/(.*)$ [NC] RewriteRule ^ https://embed.example.com%{REQUEST_URI} [L,NE,P]

However, this will send the request to https://embed.example.com/embed/34acb453bc4a53abc , not https://embed.example.com/34acb453bc4a53abc as you require.

You need to capture the part of the URL-path after /embded/ and use that instead. You are already capturing this in the RewriteCond directive, but you are not using it. You don't actually need the RewriteCond directive here.

Try the following instead:

RewriteCond %{HTTP_HOST} =subdomain.domain.com
RewriteRule ^embed/([a-z0-9]+)$ https://embed.example.com/$1 [P]

You state that the request is for subdomain.domain.com , so I've included that in the directive.

The L and NE flags are not required here. P implies L and there is nothing that requires the substitution to not be URL encoded. Slashes do not carry any special meaning in the regex, so do not need to be escaped.

I've also made the regex that matches the "code" more restrictive, rather than matching literally anything .

The $1 backreference then matches just the "code" that follows /embed/ in the URL-path.

Note that the order of directives is important. It needs to be before any directives that are likely to result in a conflict.

If the embed and subdomain hosts point to the same place on the filesystem then you can avoid the complexities and overhead of mod_proxy and simply "rewrite" the request on the same host.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM