Reputation: 18084
I have a site using static html; there aren't any PHP or CGI services available. I'd like to build a somewhat intelligent 404 error page in javascript. From JavaScript: 404 page, how to get the requested url? I understand document.referer
is not available to the receiving 404 page, however one of the answers there suggests it might be possible to pass the request url via htaccess. How might I do that? The following doesn't work:
.htaccess
:
RewriteEngine on
ErrorDocument 404 /err404.html?url=%{HTTP_REFERER}
and err404.html
:
<html><body>
<script type="text/javascript">
var file;
file = window.location.pathname;
document.write('sorry, ' + file + ' not found');
</script>
<body></html>
The resulting url remains the same as incoming, http://www.example.com/something-not-here
Upvotes: 1
Views: 777
Reputation: 785481
Enable mod_rewrite and .htaccess through httpd.conf
and then put this code in your .htaccess
under DOCUMENT_ROOT
directory:
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d # `!-d` means if directory doesn't exist
RewriteCond %{REQUEST_FILENAME} !-f # if file doesn't ...
RewriteCond %{REQUEST_FILENAME} !-l # if link doesn't
# L = last rule, stop processing
# QSA = Query String Append
# R = Redirect (default is 302, temporary)
RewriteRule ^ /err404.html?url=%{REQUEST_URI}&refr=%{HTTP_REFERER} [L,QSA,R]
Then change your err404.html like this:
<html><body>
<script type="text/javascript">
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
document.write('sorry! ' + getQueryVariable('url') +
' not found, requesting URL: ' + getQueryVariable('refr'));
</script>
<body></html>
This will result in following text getting displayed for a non-existing URI like http://domain.com/not-here
on a page http://domain.com/sample.html
sorry! /not-here not found, requesting URL: http://domain.com/sample.html
Upvotes: 2
Reputation: 71939
If I understood the question correctly, that's because window.location
will always give the URL displayed by the browser. The rewritten URL is only available on the server end, so you'll need a server-side language to accomplish that.
Upvotes: 0