I am wondering how to deal with a simple redirect. I have a domain, for example: stackguy.com. And I want to redirect users to specific URLs from this url.
Let's say, stackguy.com/redirect=youtube.com/watch/xxx
And this URL (youtube.com...) needs to be elastic. What the user enters, it should redirect to the website the user wants.
I have totally no idea, to be honest. I've tried to do it by using database and by separating all urls but it's a lot of work and can't be automated easily.
It can also be done like stackguy.com/red=<id of YT video>
Doesn't matter to me.
The other solution talks about using javascript which runs on the client side. And you probably want this on the server side.
You still need to use a parameter
stackguy.com?redirect=https://www.youtube.com/watch/xxx
But you can use php to do the redirect.
$par = filter_var ($_GET ['redirect'] ?? '', FILTER_SANITIZE_STRING);
if ($par)
{header('Location: ' . $par, true, 302); }
The first line gets the parameter after sanitizing it. It returns blank if its null (or missing)
The second line checks if there is a string
The third line does a redirect using a 302. This is a temporary redirect, I wouldn't advise using a 301 (permanent).
Note that this will only work if the PHP file has done NO HTML output.
I think you should use query parameters for this and handle the redirect in your javascript. Instead of:
stackguy.com/redirect=youtube.com/watch/xxx
use
stackguy.com?redirect=https://www.youtube.com/watch/xxx
Then in your js you can check if the redirect paramter is set and redirect the user to the link in the query parameter.
Here is an example:
function redirectUrl() {
// Get the value of the "redirect" query parameter
const redirect = new URLSearchParams(window.location.search).get("redirect");
// If the "redirect" parameter is not null, redirect the user to the specified URL
if (redirect) {
window.location = redirect;
}
}
To use the function you will need to call it in your code for example:
window.addEventListener("load", redirectUrl);
Related
Using JavaScript, how can I make it redirect to another site based on the URL?
(Example)
If someone goes to https://example.com/12345, it will redirect them to https://example.net/12345.
And if someone goes to https://example.com/abc123456, it will redirect them to https://example.net/abc123456
How can I do this?
In the place that you have hosted that domain, See if you can find something that makes it a single page app or a way to rewrite all urls to one page so that it doesn't show 404 not found. (not certain how you can do that, I only done it with firebase hosting, it has a way of configuring it so that no matter what url you give it, it always shows you the same page, and also the url doesn't get changed ) if you can do that, this is the code you need:
let pathname = location.pathname //if the url is https://example.net/1234, the path name will be /1234
location.href = "https://example.net" + pathname //if you add that to this string, it would be https://example.net/1234
You can use following code for that:
location.href = 'https://example.net/12345';
location.href = 'https://example.net/abc123456';
Or used following code for that:
location.replace('https://example.net/12345');
location.replace('https://example.net/abc123456');
All:
I have an issue with a project I am working on using C# MVC4
In the project, I am accepting a URL and other parameters from a user, then do some processing and send the result of the processing to the URL provided by the user.
The result is being sent using the following code:
var context = HttpContext.Current;
context.Response.Write("<html><head>");
context.Response.Write("</head><body>");
context.Response.Write(string.Format("<form name=\"myform\" method=\"post\" action=\"{0}\" >", postUrl));
context.Response.Write("</form>");
context.Response.Write("<script type=\"text/javascript\">document.myform.submit();</script></body></html>");
context.Response.Write("</body>");
context.Response.Flush();
context.Response.Clear();
context.ApplicationInstance.CompleteRequest();
Whenever a user attempts an XSS like passing a url value of javascript%3aalert('xss')%2f%2f, the JavaScript runs and the pop up shows up.
I've tried Antixss.HtmlEncode() to encode the URL before passing it into string.Format but still doesn't work. I've tried Antixss.UrlEncode() also, but this gives error as the form doesn't submit to the URL.
Please help me out, Is there something I am missing? What else can I do?
Thanks in advance.
You will need a three pronged approach to solve this issue.
Preventing XSS injection:
Note that if a user injected the url value
" /> <script>alert('xss')</script>
this would also leave you vulnerable:
<form name="myform" method="post" action="" /> <script>alert('xss')</script>" >
Therefore you should use the HttpUtility.HtmlAttributeEncode function to solve this one.
However, don't stop there. As noted, you should project against javascript: style URLs. For this I would ensure that the URL begins with http:// or https://. If not, throw a SecurityException which you should be logging and handling server-side, and showing the user a custom error page.
Finally, you want to protect against Open Redirect Vulnerabilities. This is to stop phishing attacks by redirecting users to other domains. Again, use a whitelist approach and ensure that the domain redirected to is one of your own. Be careful on the parsing here, as it is easy to get it wrong - a URL of http://example.org?http://example.com will pass the validation filter for example.com on many badly written validation routines. I recommend using the Uri object in .NET and retrieving the domain through that rather than rolling your own string functions.
You could also check if the URL is a relative URL, and allow it if acceptable. Use something like this function which uses a built in .NET library to ensure that it is relative or not.
Just a thought - try putting this script in rather than just document.myform.submit (and remove the form's action property):
if("{0}".indexOf('http') !== 0) {
//this is some sort of injection, or it's pointing at something on your server. Should cover http and https.
//Specifically, it makes sure that the url starts with 'http' - so a 'javascript' url isn't going to work.
} else {
document.myform.action="{0}"
document.myform.submit();
}
There is more you could do, but this should help.
Since you are adding the postUrl as an attribute "action" of the form tag, you can try using HtmlAttributeEncode method in the HttpUtility
[ValidateInput(false)]
public ActionResult Test(string url)
{
var context = System.Web.HttpContext.Current;
context.Response.Write("<html><head>");
context.Response.Write("</head><body>");
context.Response.Write(string.Format("<form name=\"myform\" method=\"post\" action=\"{0}\" >", HttpUtility.HtmlAttributeEncode(url)));
context.Response.Write("</form>");
context.Response.Write("<script type=\"text/javascript\">document.myform.submit();</script></body></html>");
context.Response.Write("</body>");
context.Response.Flush();
context.Response.Clear();
context.ApplicationInstance.CompleteRequest();
return null;
}
http://localhost:39200/home/test?url=https%3A%2F%2Fwww.google.com - Worked
http://localhost:39200/home/test?url=%3Cscript%3Ealert(%27test%27)%3C%2Fscript%3E - Worked(Did not show alert)
It is always good practice to Validate the user input against a white list of inputs, to prevent XSS exploits.
try using HttpUtility.UrlEncode
something like Response.Write(HttpUtility.UrlEncode(urlString));
see How To: Prevent Cross-Site Scripting in ASP.NET for more steps =)
How can I add something in JavaScript that will check the website URL of someone on a web site and then redirect to a certain page on the website, if a match is found? for example...
the string we want to check for, will be mydirectory, so if someone went to mysite.com/mydirectory/anyfile.php or even mysite.com/mydirectory/index.php JavaScript would then redirect their page / url to mysite.com/index.php because it has mydirectory in the URL, how can I do that using JavaScript?
If I have understood the question correctly, then it is fairly simple and can be achieved using document.URL
var search = 'mydirectory'; // The string to search for in the URL.
var redirect = 'http://mysite.com/index.php' // Where we will direct users if it's found
if(document.URL.substr(search) !== -1) { // If the location of
// the current URL string is any other than -1 (doesn't exist)
document.location = redirect // Redirect the user to the redirect URL.
}
Using document.URL you can check anything in the URL, however you might want to look into using something like Apache's mod_rewrite for redirecting the user before they even load the page.
Check out window.location, particularly it's properties and methods. You would be interested in (part of the) pathname property (you can split it on /) and the href property to change the page.
This is all assuming the javascript is being served in the first place; so I'm assuming anyfile.php and index.php would all result in the JS being served and not some 'generic 404' message.
I'm creating a custom affiliate program. I want my links to be as SEO friendly as possible, so I will use a Javascript hash appended to the URL to send the affiliate id, read the affiliate id, store the click, and then 301 re-direct to the page they were linked too. That way we have no canonical issues whatsoever, and every affiliate link passes link juice!
Now, how would I read the following URL?
www.mydomain.com/seo-friendly-url#ref=john
After getting the hash value for ref and adding the click, how would I then 301 re-direct the user back to
www.mydomain.com/seo-friendly-url
Any help is greatly appreciated!
Fragment identifiers (the part after the #) are not sent to the server, so they cannot be read by anything that could then emit an HTTP response (which you need for a 301 redirect).
The "hash" portion of a URL is not passed to the server, so you will not be able to utilize this data for any server-side redirection or processing directly. However, it is possible to grab the hash on page load and pass it on to the server via AJAX or redirection:
To immediately redirect a user from www.mydomain.com/seo-friendly-url#ref=john to www.mydomain.com/seo-friendly-url/ref/john
if (window.location.hash.match(/#ref=/))
window.location = window.location.href.replace('#ref=', '/ref/')
... but then, why not have just used www.mydomain.com/seo-friendly-url/ref/john to begin with and save the extra leg work? The other route, through AJAX, involves reading the value of the hash after the page has loaded and sending that off to the server to be recorded.
(note: this code uses a generic cross-browser XMLHTTPRequest to send an AJAX GET request. replace with your library's implementation [if you are using a library])
window.onload = function () {
// grab the hash (if any)
var affiliate_id = window.location.hash;
// make sure there is a hash, and that it starts with "#ref="
if (affiliate_id.length > 0 && affiliate_id.match(/#ref=/)) {
// clear the hash (it is not relevant to the user)
window.location.hash = '';
// initialize an XMLRequest, send the data to affiliate.php
var oXMLHttpRequest = new XMLHttpRequest;
oXMLHttpRequest.open("GET", "record_affiliate.php?affiliate="+affiliate_id, true);
oXMLHttpRequest.onreadystatechange = function() {
if (this.readyState == XMLHttpRequest.DONE) {
// do anything else that needs to be done after recording affiliate
}
}
oXMLHttpRequest.send(null);
}
}
I want to redirect after a successful ajax request (which I know how to do) but I want to pass along the returned data which will be used to load an iframe on the page I just redirected to.
What's the best way to pass such data along and use it to open and populate an iframe in the page I just redirected to?
EDIT:
I am passing a GET variable but am having to use the following to access it for use in my iframe src attribute:
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ? s=s[1] : s='';
}
var d = $_GET('thedata');
I assume there isn't really a more straightforward way to access the GET vars?
If it's not too much data, you could pass it as a get parameter in the redirect:
document.location = "/otherpage?somevar=" + urlescape(var)
Remember that urls are limited to 1024 chars, and that special chars must be escaped.
If it is beyond that limit your best move is to use server side sessions. You will use a database on the server to store the necessary information and pass a unique identifier in the url, or as a cookie on the users computer. When the new page loads, it can then pull the information out of the database using the identifier. Sessions are supported in virtually every web framework out of the box.
Another alternative may be to place the data as a hidden attribute in a form which uses the post method (to get around the 1024 char limit), and simulating a submission of the form in javascript to accomplish the redirect, including the data.