您的重写并非 100% 准确
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# IPv4
RewriteCond %{REQUEST_URI} ^/?geo/([0-9\.]+)/?$ [NC,OR]
# IPv6
RewriteCond %{REQUEST_URI} ^/?geo/([0-9a-f:]+)/?$ [NC]
RewriteRule ^.*$ /lookup.php?ip=%1 [L,QSA]
解释:
RewriteBase /geo/ 仅在您这样做时才有意义,例如RewriteRule ^.*$ lookup.php?ip=%1 [L,QSA] 和 lookup.php 实际上在 http://example.com/geo/lookup.php 中
%{REQUEST_URI} 应以 geo/<ip> 开头,这取决于您的服务器是否包含前导 /。
IP 仅包括数字 (0-9)、a-f(仅 IPv6)和 . 或 :,具体取决于 IP 地址的版本(IPv4 或 IPv6)。
目前还可以发送格式无效的 IP 地址,例如,
/geo/999..777.444 但我假设你会在你的应用程序中检查这个。
但是如果你有/geo/xx+666=765,那么它根本不会被重写。
如果你真的只想重写有效的 IP 地址而不是使用更复杂的 RegEx:
# IPv4
RewriteCond %{REQUEST_URI} ^/?geo/(((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/?$ [NC,OR]
# IPv6
RewriteCond %{REQUEST_URI} ^/?geo/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/?$ [NC]
基于来自https://stackoverflow.com/a/17871737/5427950的正则表达式
我在 Ubuntu 16.04.03 LTS 服务器和 Apache 2.4.27 上测试了这个结果