I've got a directory called /weblog.
When you enter the url (ie: my-site/weblog) for the first time ever in the browser bar, this directory should be redirected to index2.html and a cookie should be set.
This is how my .htaccess looks like:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /weblog
RewriteRule ^(.*)$ /index2.html?title=$1 [CO=title:$1&weblog:.my-site.nl:0:/]
</IfModule>
This actually works really well. When you visit the url for the first time, it gets redirected to the correct new url. No problems there.
But for some reason the cookie is not set the first time you visit the url:
let cookie = getCookie(); // returns undefined
Strangely enough, it does get set after you reload the page. But I really need the cookie the first time, because I use it to load content.
What could be going wrong and how can I fix it?
Found my answer partly after a bit more digging here: Cookie not set until a second refresh
Apparently it's not possible to access the cookie on the first load of a page. You need to reload to be able to do that.
The fix: abandon the cookie.
I now use .htaccess to add some parameters to the url (like /index2.html?title=$1
). With window.location.href
I retrieve the url from the browser, get the parameters with:
let url_string = window.location.href;
let url = new URL(url_string);
var title = url.searchParams.get('title');
// do stuff with title
and use this in the History API to change the url back to it's original form. Something similar to: history.pushState(data, null, url_string)
.
It solves my problem, but I don't like the way it shows the url with the parameters in the browser bar. Even if it is for a mere second.
Is there a way to retrieve these parameters 'under water' (not visible for visitors) from .htaccess?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.