Redirecting old anchor links to new anchor links

前端 未结 1 1549
傲寒
傲寒 2021-01-27 02:21

I\'m overhauling a website that someone else built for my organization. It was originally set up with \"not so great\" anchor links which included spaces. I have replaced those

相关标签:
1条回答
  • 2021-01-27 02:58

    As mentioned in my comment, this is not possible with .htaccess.

    Reason being: the hash part (known as the fragment) is not actually sent to the server, and so Apache would not be able to pick it up. Servers may only pick up everything before that, which is described in the Syntax section of this article.

    As an alternative, I would recommend that you use JavaScript to convert the fragment before scrolling to its location. You can do that by pulling in the value of [window.]location.hash (the part in square parenthises is optional as location is also available in the global scope) if it exists, as shown below:

    if (window.location.hash) {
    
        // Function to 'slugify' the fragment
        // @see https://gist.github.com/mathewbyrne/1280286#gistcomment-1606270
    
        var slugify = function(input) {
            return input.toString().toLowerCase().trim()
                .replace(/\s+/g, '-')           // Replace spaces with -
                .replace(/&/g, '-and-')         // Replace & with 'and'
                .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
                .replace(/\-\-+/g, '-');        // Replace multiple - with single -
        }
    
        // Now get the hash and 'slugify' it
    
        var hash = slugify(window.location.hash.split('#')[1]);
    
        // Go to the new hash by setting it
    
        window.location.hash = '#' + hash;
    
    }
    
    0 讨论(0)
提交回复
热议问题