doufu2396 2014-05-01 09:09
浏览 65
已采纳

通过htaccess从URL中抓取域名作为变量

Imagine in my website I want to show some analytic about domains, working URL example of what I need:

http://whois.domaintools.com/google.com

As you see in the above URL, it's handling google.com as a variable and pass it to another page to process the given variable, that's exactly what I want.

So for detecting that kind of variable, here is my regex:

/^[a-zA-Z\d]+(?:-?[a-zA-Z\d])+\.[a-zA-Z]+$/

The above RegEx is simple and accepts everything like: google.com, so in my .htaccess file I have:

RewriteRule (^[a-zA-Z\d]+(?:-?[a-zA-Z\d])+\.[a-zA-Z]+$) modules/pages/page.php?domain=$1

The above rule do what I want, but it also redirects my homepage to page.php while there is nothing in the URL, forexample: http://mysitename.com is now being forwarded to page.php

How can I fix this?

Thanks in advance

  • 写回答

1条回答 默认 最新

  • drduinfu915094 2014-05-01 09:58
    关注

    It redirects also the base domain to page.php because of the regex. You are using the + on all places, the meaning of the plus is "Matches the preceding pattern element one or more times.". (http://en.wikipedia.org/wiki/Regular_expression) If you request the homepage, it redirects because all the elements are appearing zero times, like you defined in the regex.

    Instead of the + you should define a minimum and a maximum amount of characters (so the zero occurrences are not evaluated). BTW, a quick search in google for "regex domain" will output a lot of results, which are tested. Use the following for example:

    RewriteEngine on
    RewriteRule (^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$) modules/pages/page.php?domain=$1
    

    Reference: Domain name validation with RegEx

    Update 1:

    If you want to use your own regex, exchange the last "+" with {2,}. The top-level domains have usually at least 2 characters.

    RewriteEngine on
    RewriteCond %{REQUEST_URI} !(\.html|\.php|\.pdf|\.gif|\.png|\.jpg|\|\.jpeg)$
    RewriteRule (^[a-zA-Z\d]+(?:-?[a-zA-Z\d])+\.[a-zA-Z]{2,}$) modules/pages/page.php?domain=$1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 咨询一下有关于王者荣耀赢藏战绩
  • ¥100 求购一套带接口实现实习自动签到打卡
  • ¥50 MacOS 使用虚拟机安装k8s
  • ¥500 亚马逊 COOKIE我如何才能实现 登录一个亚马逊账户 下发新 COOKIE ..我使用下发新COOKIE 导入ADS 指纹浏览器登录,我把账户密码 修改过后,原来下发新COOKIE 不会失效的方式
  • ¥20 玩游戏gpu和cpu利用率特别低,玩游戏卡顿
  • ¥25 oracle中的正则匹配
  • ¥15 关于#vscode#的问题:把软件卸载不会再出现蓝屏
  • ¥15 vimplus出现的错误
  • ¥15 usb无线网卡转typec口
  • ¥30 怎么使用AVL fire ESE软件自带的优化模式来优化设计Soot和NOx?