htaccess 如果请求不包含特定的字符串模式,则阻止所有请求

问题描述 投票:0回答:1

我有一个本地化的 Laravel 网站,对于该网站,我需要允许使用下面提到的 URL 模式的请求。 如果与此 URL 模式不匹配,需要导航到 404 页面。

https://www.sampledomain.ch/
https://www.sampledomain.ch/some_text/de
https://www.sampledomain.ch/some_text/it
https://www.sampledomain.ch/some_text/fr
https://www.sampledomain.ch/de
https://www.sampledomain.ch/it
https://www.sampledomain.ch/fr

任何人都可以通过 htaccess 文件指导我这样做吗?

laravel apache .htaccess mod-rewrite
1个回答
0
投票

带注释的代码

# Run this code IF "mod_rewrite" module was enabled
<IfModule mod_rewrite.c>
    # Enable server-side redirects
    RewriteEngine On

    # If the part after the domain is existed (so not just domain)
    #
    # %{REQUEST_URI}: the part after the domain
    # .+: not empty
    #
    RewriteCond %{REQUEST_URI} .+
    # AND
    # If the part after the domain not end with de, it, or fr
    #
    # %{REQUEST_URI}: the part after the domain
    # !: not
    # /(de|it|fr): /de or /it or /fr
    # $: need end of url after (de or it or fr)
    # [NC]: treats lowercase and uppercase letters equally
    #
    RewriteCond %{REQUEST_URI} !/(de|it|fr)$ [NC]
    # In that case, it returns a 404 error
    RewriteRule ^ - [R=404,L]
</IfModule>

代码

<IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteCond %{REQUEST_URI} .+
    RewriteCond %{REQUEST_URI} !/(de|it|fr)$ [NC]
    RewriteRule ^ - [R=404,L]
</IfModule>

测试用例

https://www.sampledomain.ch/ # OK (not redirected)
https://www.sampledomain.ch/some_text/de # OK (not redirected)
https://www.sampledomain.ch/some_text/it # OK (not redirected)
https://www.sampledomain.ch/some_text/fr # OK (not redirected)
https://www.sampledomain.ch/some_text/some_text/de # OK (not redirected)
https://www.sampledomain.ch/some_text/some_text/it # OK (not redirected)
https://www.sampledomain.ch/some_text/some_text/fr # OK (not redirected)
https://www.sampledomain.ch/de # OK (not redirected)
https://www.sampledomain.ch/it # OK (not redirected)
https://www.sampledomain.ch/fr # OK (not redirected)

https://www.sampledomain.ch/some_text/DE # OK (not redirected)
https://www.sampledomain.ch/some_text/It # OK (not redirected)
https://www.sampledomain.ch/some_text/rF # OK (not redirected)
https://www.sampledomain.ch/De # OK (not redirected)
https://www.sampledomain.ch/iT # OK (not redirected)
https://www.sampledomain.ch/FR # OK (not redirected)

https://www.sampledomain.ch/FR123 # 404 error
https://www.sampledomain.ch/fr/test # 404 error
https://www.sampledomain.ch/a # 404 error

etc.
© www.soinside.com 2019 - 2024. All rights reserved.