简体   繁体   中英

How to remove index.php from to url with jquery?

I like to remove index.php from the url with jquery

I try this code but continuously reload the page

$(document).ready(function(){
   var href=document.location.href;
   if(href.indexOf("index.php")){
       document.location.href = href.replace( "index.php", "" );
   }   
});

How to remove and dont continuously reload page ?

You can use history object to achieve this.

history.pushState(null,pagetitle,chageUrL);

where pagetitle is the new page title if that requires to be changed and changeUrl is the new url you want to set

But remember this is not supported by IE v <8

Refer to below links for better understanding on this:

Modify the URL without reloading the page
http://www.w3schools.com/jsref/obj_history.asp
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

Actually no need to jQuery here, raw JavaScript is enough

the problem with your code is you are comparing with -1 which is in JavaScript truly value

if(-1){ alert('i am here') /* the code here will be executed */}

and you can try this in your console: !!-1 // => true

so you have to check if its greater than -1 or 0 (since here index.php cannot be at the beginning of the string)

if(window.location.href.indexOf('index.php') > -1) // or 0 
window.location.href = window.location.href.replace('index.php', '');

I would say its a wrong logic to do it on the client side. In fact you cant(should'nt) edit the url for cosmetic purposes on the client side.

You can do this with an htaccess mod on the Server Side (ASSUMING YOU HAVE AN APACHE SERVER, SINCE YOU ARE EDITING A PHP PAGE IN THE URL) . Add the below line to your htaccess file in the server directory(where your page is situated)

for example in www.example.com/test , put the below line in the test directory ('.htaccess') file

DirectoryIndex index.php index.html site-down.php

so when you go to www.example.com/test you get the index.php page.

Don't edit URL's on client side ! This is not a good practice as well as not good for SEO.
Even if you have some different server like nGinx / ISIS etc.. Do it properly on the server side where it should be done ! I can undertand if it was for removing an "#id" etc.. from the url
for which your existing code is appropriate. But editing target pages is a no no !

I recommend you to read an existing stackOverflow page..
Apache friendly urls
to create true user+seo friendly url's.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM