0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ApacheのRewriteでNOT条件を使用したい場合

Posted at

Let's Encryptの.well-known、アドセンスのads.txtにはアクセスを許可して、それ以外は別サイトにリダイレクトしたい時ってありませんか?

良くあるのは、.well-knownディレクトリ内へのアクセスはそのまま通して、それ以外はリダイレクトしたいって場合です。

そんな時にはRewriteのNOT条件を使います。通常の条件は、パターンにマッチすればリダイレクトとなりますが、NOT条件の場合はパターンにマッチするとリダイレクトしないとなります。

と言うわけで、論より証拠、実際の例を見ていきましょう。

.well-knownのみアクセスを許可して、それ以外は別サイトにリダイレクトする場合

RewriteEngine On
RewriteCond %{REQUEST_URI} !/^\.well-known
RewriteRule ^(.*)$ https://rgz95.com%{REQUEST_URI} [R=301,L]

ads.txtのみアクセスを許可して、それ以外は別サイトにリダイレクトする場合

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/ads\.txt
RewriteRule ^(.*)$ https://rgz95.com%{REQUEST_URI} [R=301,L]

.well-known・ads.txtのみアクセスを許可して、それ以外は別サイトにリダイレクトする場合

RewriteEngine on
RewriteCond %{REQUEST_URI} !^/\.well-known
RewriteCond %{REQUEST_URI} !^/ads\.txt
RewriteRule .* https://rgz95.com%{REQUEST_URI} [R=301,L]

まとめ

Rewriteでは条件の先頭に「!」をつけることでNOT条件になります。

「!」が先頭につかない通常の条件ではパターンにマッチすればRewriteRule実行と言う条件になりますので、逆の意味になります。「!」がついた場合はパターンにマッチしたらRewriteRuleを実行しないという流れになります。

何かの参考になれば幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?