modifies header to sent redirect location by GiroCheckout
9785
public function redirectCustomerToPaymentProvider() {
    if (isset($this->response['redirect'])) {
      header('location:' . $this->response['redirect']);
      exit;
    }
    elseif (isset($this->response['url'])) {
      header('location:' . $this->response['url']);
      exit;
    }
  }
145312
def handleHeader(self, key, value):
        ""
        key_lower = key.lower()
        if key_lower == 'location':
            value = self.modLocationPort(value)
        self._response.headers[key_lower] = value
        if key_lower != 'cache-control':
            # This causes us to not pass on the 'cache-control' parameter
            # to the browser
            # TODO: we should have a means of giving the user the option to
            # configure how they want to manage browser-side cache control
            proxy.ProxyClient.handleHeader(self, key, value)
827112
def _add_redirects(self):
        
        html = '''
        <html>
            <head>
                <meta http-equiv="refresh" content="0;URL={url}"/>
            </head>
            <body>
                <p>
                    The page has been moved to <a href="{url}">{title}</a>
                </p>
            </body>
        <html>
        '''
        with open(REDIRECTS_FILE) as mapping_fd:
            reader = csv.reader(mapping_fd)
            for row in reader:
                if not row or row[0].strip().startswith('#'):
                    continue

                path = os.path.join(BUILD_PATH,
                                    'html',
                                    *row[0].split('/')) + '.html'

                try:
                    title = self._get_page_title(row[1])
                except Exception:
                    # the file can be an ipynb and not an rst, or docutils
                    # may not be able to read the rst because it has some
                    # sphinx specific stuff
                    title = 'this page'

                if os.path.exists(path):
                    raise RuntimeError((
                        'Redirection would overwrite an existing file: '
                        '{}').format(path))

                with open(path, 'w') as moved_page_fd:
                    moved_page_fd.write(
                        html.format(url='{}.html'.format(row[1]),
                                    title=title))
843443
function(url) {
      if (!isSupportHistoryAPI && ('' + url).indexOf('#') === 0) {
        changeState(null, url, true);
      } else {
        windowLocation.replace(url);
      }
    }
401147
function attachRedirect(router, { path, redirect }, site) {
  redirect = normalizeRedirectPath(redirect, site);

  return router.get(path, (req, res) => {
    res.redirect(301, redirect);
  });
}
1305706
public function sendRedirect($location, $status = 302)
    {
        if (!is_int($status) || $status < 300 || $status > 399) {
            return;
        }
        
        if ($location[0] != '/' && !preg_match("/^[0-9a-z]+:\\/\\//i", $location)) {
            $location = $this->baseUrl . $location;
        }
        
        $this->clearHeaders();
        $this->addHeader('Location', $location, true);
        $this->setStatus($status);
        $this->isRedirect = true;
        $this->sendHeaders();
        
        exit();
    }
1180590
def _process_redirect(self):
        ''''''
        _logger.debug('Handling redirect.')

        if self._redirect_tracker.exceeded():
            raise ProtocolError('Too many redirects.')

        try:
            url = self._redirect_tracker.next_location()

            if not url:
                raise ProtocolError('Redirect location missing.')

            if self._redirect_tracker.is_repeat():
                _logger.debug('Got redirect is repeat.')

                request = self._original_request.copy()
                request.url = url
            else:
                request = self._request_factory(url)

            request.prepare_for_send()
        except ValueError as error:
            raise ProtocolError('Invalid redirect location.') from error

        self._next_request = request

        _logger.debug('Updated next redirect request to {0}.'.format(request))
67224
def follow_redirection request = nil, result = nil, & block
      url = headers[:location]
      if url !~ /^http/
        url = URI.parse(args[:url]).merge(url).to_s
      end
      args[:url] = url
      if request
        if request.max_redirects == 0
          raise MaxRedirectsReached
        end
        args[:password] = request.password
        args[:user] = request.user
        args[:headers] = request.headers
        args[:max_redirects] = request.max_redirects - 1
        # pass any cookie set in the result
        if result && result['set-cookie']
          args[:headers][:cookies] = (args[:headers][:cookies] || {}).merge(parse_cookie(result['set-cookie']))
        end
      end
      Request.execute args, &block
    end
1125841
def redirect(url, code=303):
    
    scriptname = request.environ.get('SCRIPT_NAME', '').rstrip('/') + '/'
    location = urljoin(request.url, urljoin(scriptname, url))
    raise HTTPResponse("", status=code, header=dict(Location=location))
1204797
function Request_redirect(url, isTemp) {
        logger.info('Request.redirect:', {
            url: url,
            isTemp: isTemp
        });
        this.addHeader('Location', url);
        this.stopPromiseChain();
        this.isRendered = true;
        if (Type.isBoolean(isTemp) && !!isTemp) {
            this.response.writeHead(302, this.headers);
        } else {
            this.response.writeHead(301, this.headers);
        }
        this.response.end('Redirect to:' + url);
    }
358933
private function redirectPost()
    {
        if (!isset($_SERVER['REQUEST_URI'])) {
            return;
        }
        if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] != 'POST') {
            return;
        }
        if (!$this->cfg['prg']) {
            return;
        }
        if (!$this->status['submitted']) {
            return;
        }
        $this->debug->log('redirecting');
        $event = $this->eventManager->publish('page.redirect', null, array('location' => $_SERVER['REQUEST_URI']));
        $location = $event['location'];
        $this->debug->log('%cLocation:%c <a href="%s">%s</a>', 'font-weight:bold;', '', $location, $location);
        if (\headers_sent($file, $line)) {
            $this->debug->warn('headers alrady sent from '.$file.' line '.$line);
            return;
        }
        if ($event->isPropagationStopped()) {
            $this->debug->alert('<i class="fa fa-external-link fa-lg" aria-hidden="true"></i> Location: <a class="alert-link" href="'.\htmlspecialchars($location).'">'.\htmlspecialchars($location).'</a>', 'info');
        } else {
            \header('Location: '.$location);
        }
        throw new \Exception('exit');
    }
459887
def update_redirect(self):
        
        page_history = Stack(session.get("page_history", []))
        page_history.push(request.url)
        session["page_history"] = page_history.to_json()
112181
public function redirect($url, $header=301)
    {
        $this->disableLayout();
        $this->setNoRender();

        $this->_params["dispatcher"]->clearHeaders();
        $this->_params["dispatcher"]->addHeader("Location", $url, $header);
    }
817954
function redirect( /* mixed */ )
	{
		/*
			Taken from: http://www.php.net/manual/en/function.header.php#78470

			// 301 Moved Permanently
			header("Location: /foo.php",TRUE,301);

			// 302 Found
			header("Location: /foo.php",TRUE,302);
			header("Location: /foo.php");

			// 303 See Other
			header("Location: /foo.php",TRUE,303);

			// 307 Temporary Redirect
			header("Location: /foo.php",TRUE,307);

			"The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time.  Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely.  Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307."

			"If the status code is not specified, header('Location:') defaults to 302."
		*/
		$http_response_code = 302;
		$location = null;
		$args = func_get_args();
		if (count($args) === 1 && is_string($args[0]))
		{
			$arg = $args[0];
			switch ($arg[0])
			{
				case '/':
					$location = $arg;													//	$arg == '/path' || $arg == '//host/path'
					break;
				case 'h':
					if ($arg === 'http' || $arg === 'https')
						$location = (string) $this->uri->withScheme($arg);				//	'//' . $this->uri->authority . $this->uri->getPathAndQuery();
					//	$location = $arg . '://' . _::request('host') . _::request('uri');
					else
						$location = $arg;												//	$arg == 'http://www.google.com/'
					break;
				case '?':
					$location = $this->uri->getLeftPart(Uri::PARTIAL_PATH) . $parts;	//	(_::is_https() ? 'https://' : 'http://') . _::request('host') . _::request('path') . $parts;
					//$location = _::request('path') . $arg;
					break;
				case '&':	// append to query string
					$location = $this->uri->getLeftPart(Uri::PARTIAL_QUERY);
					$location .= strpos($location, '?') === false ? '?' . substr($arg, 1) : $arg;
				//	$location .= ($location->query === null ? '?' . substr($arg, 1) : $arg);	//	alternative using Uri object!
					//$location = _::request('uri') . (empty(_::request('query')) ? '?' . substr($arg, 1) : $arg);
					break;
				case '#':
					$location = $this->uri->getLeftPart(Uri::PARTIAL_QUERY);
				//	$location = _::request('uri') . $arg;
					break;
				default:
					$location = $arg;
			}
		}
		else
		{
			throw new \Exception('Request section not implemented/RE-written yet!');

			/*
			//	Note: This is not necessary because the redirect header accepts a path based address; eg. / ... so the scheme & host are NOT always required! IOW we don't need to build a FULL / fully qualified URL like the `build_url()` function!
			$location = [	'scheme'		=>	self::$https ? 'https' ; 'http',
							'host'			=>	self::$host,
							'path'			=>	self::$path,
							'query'			=>	self::$query
						];
			*/
			foreach ($args as $arg)
			{
				if (is_string($arg))
				{
					switch (substr($arg, 0, 1))						//	pseudo: if $arg = '' then $arg[0] == `Notice: Uninitialized string offset: 0` ... IOW: We cannot use `switch($arg[0])` because we could get a PHP notice message!
					{
						case '/':
							if (substr($arg, 0, 2) === '//')		//	`//` eg. '//www.google.com/' ... ie. same protocol!
								$location = parse_url($arg);
							else									//	`/` eg. '/login' ... ie. relative URL
							{
								$qmark = strpos($arg, '?');
								if ($qmark === false)				//	eg. request::redirect('https', '/login')	...	ie. the `https` will set scheme, host, path and query. We only want scheme, host and path! NOT the query string!
								{
									$location['path'] = $arg;
									unset($location['query']);
								}
								else								//	eg. request::redirect('/login?id=123', '?id=456')
								{
									$location['path'] = substr($arg, 0, $qmark);
									$location['query'] = substr($arg, $qmark + 1);
								}
							}
							break;
						case '?':
							//	if ( ! isset($location['path']))	//	optional
							//		$location['path'] = self::$path;
							$location['query'] = substr($arg, 1);	//	overwrite existing query string  OR  create/set query string
							break;
						case '&':
							//	if ( ! isset($location['path']))	//	optional
							//		$location['path'] = self::$path;
							$location['query'] = (empty($location['query']) ? substr($arg, 1) : $location['query'] . $arg);	//	append to existing query string  OR  create new query string if it doesn't exist
							break;
						case '#':
							//	if ( ! isset($location['path']))	//	optional
							//		$location['path'] = self::$path;
							$location['fragment'] = substr($arg, 1);	//	should it be possible to just set the fragment without anything else?
							break;
						case 'h':
							if ($arg === 'http' || $arg === 'https')
							{
								$location = [	'scheme'		=>	$arg,
												'host'			=>	_::request('host'),
												'path'			=>	_::request('path'),
												'query'			=>	_::request('query')
											];
								break;
							}
							//	Alternative version below would have checked the prefix value of $arg for a `http:/` or `https:` value in the beginning to `semi-validate` the parse_url() value.
							//$substr = substr($arg, 0, 6);							//	`optional` alternative
							//if ($substr === 'http:/' || $substr === 'https:')
							//{
								$location = parse_url($arg);
								break;
							//}
							//	fallthrough vvv if NOT `http://` or `https://`
						default:
							die('Invalid value in request::redirect(): ' . print_r($arg, true));
							/*
							if (strpos($arg, '=') !== false)	//	eg. 'test=123' == append to query string
							{
								$location = [	'scheme'		=>	$arg,
												'host'			=>	self::$host,
												'path'			=>	self::$path,
												'query'			=>	self::$query
											];
							}
							*/
					}
				}
				else if (is_int($arg))
					$http_response_code = $arg;
				else if (is_array($arg))
				{
					if (is_array($location))
					{
						if (isset($location['query']) && isset($arg['path']) && ! isset($arg['query']))	//	eg. request::redirect('?id=123', ['path' => '/']) ... result = '/' ... because the '/' is a PATH without query string! The new `arg` value has a PATH but NOT a query string! path = query string = request_uri ... they go hand-in-hand!
							unset($location['query']);
						$location = array_merge($location, $arg);
					}
					else
						$location = $arg;
				}
				else
					die('Invalid value in request::redirect(): ' . print_r($arg, true));
			}

			if (is_array($location))
			{
				throw new \Exception('Request section not implemented or re-written yet!');

				if (isset($location['scheme']) && ! isset($location['host']))
					$location['host'] = _::request('host');

				if (isset($location['user']) || isset($location['pass']))
					$location['host'] = (isset($location['user']) ? $location['user'] : null) . (isset($location['pass']) ? ':' . $location['pass'] : null) . '@' . (isset($location['host']) ? $location['host'] : _::request('host'));

				if (isset($location['host']) && ! isset($location['path']))
					$location['path'] = '/';

				$location = (isset($location['scheme'])   ? $location['scheme'] . ':' : null) .
							(isset($location['host'])     ? '//' . $location['host'] . (isset($location['port']) ? ':' . $location['port'] : null) : null) .
							(isset($location['path'])     ? $location['path'] : null) .
							(isset($location['query'])    ? '?' . $location['query'] : null) .
							(isset($location['fragment']) ? '#' . $location['fragment'] : null);
			}
			else
				die('Invalid value in request::redirect(): ' . print_r($args, true));
		}

		// ob_get_length() will return "FALSE if no buffering is active." ... so all we want to know is if buffering IS active AND there was already data sent to the buffer ... then we need to die()!
		if (ob_get_length()) die(ob_get_clean() . '<p><span style="color: red;">Errors on Redirect to: <a href="' . $location . '">' . $location . '</a></span></p>');
		if ( ! headers_sent($filename, $linenum))
		{
			if ( ! empty($location) ) header('Location: ' . $location, true, $http_response_code);
			else echo '<p><span style="color: red"><b>ERROR: Empty location on redirect()!</b></span></p>';
			exit;
		}
		throw new \Exception("<p><span style='color: red'>ERROR:</span> <b>Headers already sent</b> in `{$filename}` on line <b>`{$linenum}`<br />" .
			"Cannot redirect, please click the following link: <a href='{$location}'>{$location}</a></p>");
	}
304713
def set_redirect(self, url, status=HttpStatusCodes.HTTP_303):
        
        self.set_status(status)
        self.set_content('')
        self.set_header(HttpResponseHeaders.LOCATION, url)
1072503
function(options, callback, opt_data) {
  var request = http.request(options, function(response) {
    if (response.statusCode == 302 || response.statusCode == 303) {
      try {
        var location = url.parse(response.headers['location']);
      } catch (ex) {
        callback(Error(
            'Failed to parse "Location" header for server redirect: ' +
            ex.message + '\nResponse was: \n' +
            new HttpResponse(response.statusCode, response.headers, '')));
        return;
      }

      if (!location.hostname) {
        location.hostname = options.host;
        location.port = options.port;
      }

      request.abort();
      sendRequest({
        method: 'GET',
        host: location.hostname,
        path: location.pathname + (location.search || ''),
        port: location.port,
        headers: {
          'Accept': 'application/json; charset=utf-8'
        }
      }, callback);
      return;
    }

    var body = [];
    response.on('data', body.push.bind(body));
    response.on('end', function() {
      var resp = new HttpResponse(response.statusCode,
          response.headers, body.join('').replace(/\0/g, ''));
      callback(null, resp);
    });
  });

  request.on('error', function(e) {
    if (e.code === 'ECONNRESET') {
      setTimeout(function() {
        sendRequest(options, callback, opt_data);
      }, 15);
    } else {
      var message = e.message;
      if (e.code) {
        message = e.code + ' ' + message;
      }
      callback(new Error(message));
    }
  });

  if (opt_data) {
    request.write(opt_data);
  }

  request.end();
}
1228795
def do_HEAD(self):
        """"""
        self.queue.put(self.headers.get("User-Agent"))
        self.send_response(six.moves.BaseHTTPServer.HTTPStatus.OK)
        self.send_header("Location", self.path)
        self.end_headers()