htaccess merge 2 segments with underscore

2019-05-31 23:46发布

I want to merge 2 segments into 1 using underscore.

Example:
http://example.com/main/id_id/someurl
should point to
http://example.com/main/id/id/someurl

What I got so far as I understand htaccess:

RewriteEngine On
RewriteBase /main/
RewriteCond %{REQUEST_URI} ^/main/id_id(.*)$
RewriteRule .* http://example.com/main/id/id%1 [L]

But accessing http://example.com/main/id_id just redirects to http://example.com/main/id/id. I'm wondering why it is redirecting since I didn't use R flag

Also as simple as:

RewriteEngine On
RewriteBase /main/
RewriteRule ^main/id_id$ /main/id/id/ [L]

Should work, but it's not. Any help would be appreciated.

Edit: I think this is a wordpress thing. I can mask direct access to directories like images but I cannot mask pages

1条回答
Fickle 薄情
2楼-- · 2019-06-01 00:30

But accessing http://example.com/main/id_id just redirects to http://example.com/main/id/id. I'm wondering why it is redirecting since I didn't use R flag.

If you specify an absolute URL (ie. scheme + Hostname) in the RewriteRule substitiution then Apache will implicitly trigger an external (302) redirect, regardless of whether you've explicitly included the R flag or not.

RewriteRule ^main/id_id$ /main/id/id/ [L]

Should work, but it's not.

WordPress routes the URL based on the initial request URL (ie. the value of the $_SERVER['REQUEST_URI'] PHP superglobal), not the rewritten URL. So, yes, this is a "WordPress thing". You would need to create an additional "route" for this URL (not rewrite it). However, this potentially creates issues with duplicate content etc.

However, if you are changing an existing URL that has perhaps been linked to and indexed by search engines then this arguably should be a 301 external redirect and not an internal rewrite.


RewriteBase /main/
RewriteCond %{REQUEST_URI} ^/main/id_id(.*)$
RewriteRule .* http://example.com/main/id/id%1 [L]

This can be simplified to a single directive:

RewriteRule ^main/id_id(.*) /main/id/id$1 [R,L]

The RewriteBase directive is not doing anything here. The RewriteBase directive simply states the URL-path that should be used for relative path substitutions.

查看更多
登录 后发表回答