douqu2481 2017-01-03 18:12
浏览 37

使用JavaScript将子域重定向到域

I am using Apache envvars for creating the MYDOMAIN and MYSUBDOMAIN variables where I define 'mydomain.com' and 'sub.mydomain.com'. I then use these variables in the apache sites-available conf files to deploy the website. The 'sub' subdomain resides in /var/www/html/sub/. I need to have a JavaScript function on the subdomain website check whether or not a particular file exists in /var/www/html and if so, redirect to that location (i.e. mydomain.com). I cannot hard-code any specific URL's - these will be dealt with strictly using apache envvars, so I need a solution that will work regardless what the domain/subdomain is.

For this purpose, I am using AJAX like this, if file.txt returns a success, redirect to the /index.php:-

$(document).ready(function() {

            $.ajax({
                type: 'HEAD',
                url: '/file.txt',
                success: function() {
                            setInterval(function () {
                                    location.replace("/index.php");
                            }, 5000);
                },
                error: function() {
                            console.log('404 Not Found');
                }
            });
});

Unfortunately the document root for the subdomain is /var/www/html/sub therefore /file.txt and /index.php are effectively being looked for in /var/www/html/sub/ - I need this to look for file.txt in /var/www/html/ and then redirect to /var/www/html/index.php.

I also tried using '../file.txt' and '../index.php' but this returns the same result (i.e. '404 Error' is logged because it is looking for what is essentially /var/www/html/sub/file.txt). Since I cannot access the apache envvars from JS (I think - would be a major security scare if I could!!) - what other options have I got?

Thanks!

展开全部

  • 写回答

1条回答 默认 最新

  • dounan4479 2017-01-03 18:59
    关注

    var hostFileUrl = function(fileName){
      return window.location.protocol + "://" + window.location.hostname + "/" + fileName;
    };
    
    $(document).ready(function() {
      $.ajax({
        type: 'HEAD',
        url: hostFileUrl('file.txt'),
        success: function(){
          setInterval(function(){
            window.location.assign(hostFileUrl("index.php"));
          }, 5000);
        },
        error: function(){
          console.log('404 Not Found');
        }
      });
    });

    </div>
    
    评论
    编辑
    预览

    报告相同问题?

    手机看
    程序员都在用的中文IT技术交流社区

    程序员都在用的中文IT技术交流社区

    专业的中文 IT 技术社区,与千万技术人共成长

    专业的中文 IT 技术社区,与千万技术人共成长

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

    客服 返回
    顶部