You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从THE_REQUEST提取纯路径至变量的htaccess规则精简需求

Extract Clean Path from THE_REQUEST with .htaccess (Simplified)

Hey argon, nice work getting the multi-line solution working—let’s condense that into a couple of concise, elegant rules that cover every edge case you listed perfectly.

The Simplified Rules

# Extract clean path (strip trailing slashes & query strings)
RewriteCond %{THE_REQUEST} \s/+([^\s?]+)(?:/?\?|\s)
RewriteRule ^ - [E=TRGT:%1]

# Explicitly set empty value for root requests
RewriteCond %{THE_REQUEST} \s/(?:\s|\?)
RewriteRule ^ - [E=TRGT:]

How It Works

Let’s break down each rule to show it handles all your requirements:

  1. Main Path Extraction Rule

    • The regex \s/+([^\s?]+)(?:/?\?|\s) targets the path segment in THE_REQUEST:
      • \s/+ matches the space before the request path, plus any leading slashes (so it ignores the initial /)
      • ([^\s?]+) captures the core path—this matches everything that’s not a space or question mark, so it automatically excludes query strings
      • (?:/?\?|\s) matches either an optional trailing slash followed by a query string, or the closing space of the request line. This ensures trailing slashes are stripped from the captured value.
    • This single rule handles paths with extensions, subfolders, trailing slashes, and query strings all in one pass.
  2. Root Request Handling

    • The regex \s/(?:\s|\?) matches root-level requests (like GET / HTTP/1.1 or GET /?foo=bar HTTP/1.1).
    • It explicitly sets the TRGT environment variable to an empty string, which aligns with your requirement of having an empty/undefined value for the root domain.

Test Case Verification

All your expected scenarios are covered:

  • example.com → TRGT= (empty)
  • example.com/ → TRGT= (empty)
  • example.com/some-word → TRGT=some-word
  • example.com/some-word/ → TRGT=some-word
  • example.com/some-word/?foo=bar → TRGT=some-word
  • example.com/another_word/ → TRGT=another_word
  • example.com/folder/file.ext → TRGT=folder/file.ext
  • example.com/some/other.dot?bar=foo → TRGT=some/other.dot
  • example.com/thing.ext/?foo=bar&bar=foo → TRGT=thing.ext

Why This Beats the Multi-Line Approach

  • Reduces 4 conditional rules to just 2, eliminating redundant processing
  • Uses a single regex capture to handle trailing slashes and query strings simultaneously
  • Explicitly addresses root requests without relying on multiple conditional passes, making the logic clearer and more efficient

内容的提问来源于stack exchange,提问作者argon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 07:27:38