apache - .htaccess 规则从 url 中跳过 $2 不匹配的 uri 段

标签 apache .htaccess redirect mod-rewrite friendly-url

我想要下面的请求和响应

RewriteEngine On

#Check for files that do not contain the language string
RewriteCond %{REQUEST_URI} !^/[a-z]{2}/.*
RewriteRule ^(.*)$ https://%{HTTP_HOST}/en [R=301,L]

#Capture the language string and present it as the variable
RewriteCond %{REQUEST_URI} ^/([a-z]{2})/
RewriteRule ^([a-z]{2})/(.*)$ https://%{HTTP_HOST}/%1/%2 [R=301,L]

尝试对 %2 段 uri 进行一些更改,但到目前为止没有任何帮助,有人早些时候做过吗? 让我知道是否需要更多描述

最佳答案

根据您展示的示例/尝试,请尝试执行以下操作。请确保在测试您的 URL 之前清除您的浏览器缓存。

将这些规则放在 .htaccess 规则文件的顶部。我假设您有规则来为您的 htaccess 规则文件中新重写的 url 提供服务。

RewriteEngine ON
##1st kind of urls, to remove / from end of it.
RewriteRule ^([a-zA-Z]{2})/?$ $1 [R=301,L]

##Handle https://example.com/de/fr/en/de/en TO https://example.com/de urls.
RewriteRule ^([a-zA-Z]{2})/(?:[a-zA-Z]{2}/)*(?:[a-zA-Z]{2})/?$ $1 [R=301,L]

##Handle https://example.com/de/fr/path TO https://example.com/de/path urls.
RewriteRule ^([a-zA-Z]{2})/(?:[a-zA-Z]{2}/)*(.*)/?$ $1/$2 [R=301,L]

##handle https://example.com/def/frq/path TO https://example.com/en urls here.
RewriteRule ^([a-zA-Z]{3,})/.*$ en [R=301,L]

Online demo for 3rd rule regex

Online demo for 2nd rule regex



编辑: 或者检查以 2 个字母的特定语言开头的规则然后尝试以下,我使用过 en、us、de、fr 语言,您可以添加也可以根据您的需要添加更多内容。

RewriteEngine ON
##1st kind of urls, to remove / from end of it.
RewriteRule ^(en|us|de|fr)/?$ $1 [NC,R=301,L]

##Handle https://example.com/de/fr/en/de/en TO https://example.com/de urls.
RewriteRule ^(en|us|de|fr)/(?:(?:en|us|de|fr)/)*(?:en|us|de|fr)/?$ $1 [NC,R=301,L]

##Handle https://example.com/de/fr/path TO https://example.com/de/path urls.
RewriteRule ^(en|us|de|fr)/(?:(?:en|us|de|fr)/)*(.*)/?$ $1/$2 [NC,R=301,L]

##handle https://example.com/def/frq/path TO https://example.com/en urls here.
RewriteRule ^([a-zA-Z]{3,})/.*$ en [R=301,L]

关于apache - .htaccess 规则从 url 中跳过 $2 不匹配的 uri 段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68032530/

相关文章:

apache - 如何在 .htaccess 中为特定 IP 地址设置 cookie

php - Heroku PHP 和 Apache dyno 崩溃并出现错误 H10

wordpress - 使用 .htaccess 将帖子从一个类别重定向到新的 URL

.htaccess - htaccess : redirect all requests to different domain (without query arguments)

asp.net - FormsAuthentication.RedirectFromLoginPage 与 Response.Redirect

bash - 将多个 stdout 命令重定向到一个文件

php - Apache/Httpd 与 PHP 5.5 一起使用的 httpd_module 名称是什么?

.htaccess url 为 ssl https 重定向重写

apache - 我如何在 Apache http mod_rewrite 中使用原子作为路径变量?

database - 如何使用单引号从 Apache Usergrid 中选择实体